Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I would like to replace the string "The quick brown fox jumps over the lazy dog" with the string "The1 quick2 brown3 fox4 jumps5 over6 the7 lazy8 dog9".

Is there an cleaner, more elegant, sexier way?

String.prototype.concatWordNumber = function() {

   var myArray = this.split(' ');
   var myString = "";
   for (var i=0, len = myArray.length; i<len; i++)
   {      
        myString += myArray[i]+[i+1]+ " " ;
   }
  return myString;
}

var text = "The quick brown fox jumps over the lazy dog";

console.log(text.concatWordNumber());
share|improve this question

1 Answer 1

up vote 3 down vote accepted

Is there an cleaner, more elegant, sexier way?

I guess regex makes it more elegant and sexier, but your implementation is fine:

String.prototype.concatWordNumber = function() {
  var i = 1;
  return this.replace(/\b\w+\b/g, function(word) {
    return word + i++;
  });
};

Or you could use map:

String.prototype.concatWordNumber = function() {
  var plusIdx = function(x,i) {
    return x + ++i;
  };
  return this.split(' ').map(plusIdx).join(' ');
};
share|improve this answer
    
"the quick brown fox " returns "the1 quick2 brown3 fox4 5 6". Maybe return x.trim() ? x + ++i : x; would fix it? But maybe its not worth it. –  James Khoury Jan 21 '14 at 0:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.