0

I need to replace text using Javascript. It's a little different than the other ones I've seen on S.O. because the text that needs to be added in is an incrementing integer.

For example: Replace the string: "John Mary Ellen Josh Adam" with "John1 Mary2 Ellen3 Josh4 Adam5"

2
  • So what precisely do you want to do? Append a number to each word, where "word" is defined as consecutive alphabetical characters, separated by white spaces? Commented Mar 21, 2012 at 14:24
  • how you know you have to add the integer.. if there is a space can you add it. What is the condition tocheck Commented Mar 21, 2012 at 14:25

5 Answers 5

6

Use a callback replacer:

var str = "John Mary Ellen Josh Adam", i=0;
str = str.replace(/ /g,function(m) {i++; return i+" ";});

EDIT: Noticed that won't add a number after "Adam". That can be fixed just by adding:

i++; str += i;

at the end of the code.

EDIT2: Or all-in-one:

str = str.replace(/ |$/g,function(m) {i++; return i+m[0];});
Sign up to request clarification or add additional context in comments.

4 Comments

About adding a number after "Adam": you could also adjust the regex to match the end of the string, e.g. str.replace(/ |$/g, ....
That would add an extra space on the end, though, because of what the function returns.
I liked this - especially the elegance of it - but felt it better to use the jsfiddle option rather than adding in an extra line of code. Perhaps that's just my inexperience.
you could also match the words instead of the spaces, see my answer. That way John  Mary (two spaces) yields John1  Mary2, not John1 2 Mary3
2

You can do it this way:

var array = string.split(" "), i, j;

for(i=0,j=array.length,string="";i<j;string+=array[i]+(++i)+" ");

Comments

1
var input = "John Mary Ellen Josh Adam";

var i = 0;
var output = input.replace(/\w+/g, function(m){ return m + ++i });

output is:

"John1 Mary2 Ellen3 Josh4 Adam5"

1 Comment

Couldn't RegExp.lastMatch be replaced with the 1st parameter passed to the callback? Which is more efficient?
0

I quickly hacked this up. Not sure how efficient it is, but it works.

var x = 1, str = "John Mary Ellen Josh Adam",
newStr = str.replace(/\b([^\s]*)\b/g, function(i){
    return i && (i + (x++));
});

Comments

0

I put together this jsfiddle for you.

This is the code:

var originalStr = "John Mary Ellen Josh Adam";
var splitStr = originalStr.split(' ');
var newStr = "";
for (var i = 0; i < splitStr.length; i++)
    newStr += splitStr[i] + (i+1) + ' ';

alert(newStr);

3 Comments

Please include the code in your answer as well as some explanation.
This results in a trailing space on the string.
i agree @robmisio, that shouldn't be happening

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.