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"
-
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?Felix Kling– Felix Kling2012年03月21日 14:24:53 +00:00Commented 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 tocheckzod– zod2012年03月21日 14:25:13 +00:00Commented Mar 21, 2012 at 14:25
5 Answers 5
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];});
4 Comments
str.replace(/ |$/g, ....John Mary (two spaces) yields John1 Mary2, not John1 2 Mary3You 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
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
RegExp.lastMatch be replaced with the 1st parameter passed to the callback? Which is more efficient?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
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);