I am using the below function to replace words beginig with # from the string, with variables of exact same name from the extra_data object.
var messageString = "The folder #folder_name was removed from the workspace #workspace_name by #user_name"
var re = /(?:^|\W)#(\w+)(?!\w)/g, match;
while (match = re.exec(messageString)) {
messageString = messageString.replace(match[0],extra_data[match[1]]);
console.log("I am here--------------------------------------------->1");
console.log(messageString);
}
Console log
I am here--------------------------------------------->1
The folder23545 was removed from the workspace #workspace_name by #user_name
I am here--------------------------------------------->1
The folder23545 was removed from the workspace127 by #user_name
The above code replaces only 2 instances and sometimes eats up white space also as you can see at workspace127. What am i doing wrong?
I am using the below function to replace words beginig with # from the string, with variables of exact same name from the extra_data object.
var messageString = "The folder #folder_name was removed from the workspace #workspace_name by #user_name"
var re = /(?:^|\W)#(\w+)(?!\w)/g, match;
while (match = re.exec(messageString)) {
messageString = messageString.replace(match[0],extra_data[match[1]]);
console.log("I am here--------------------------------------------->1");
console.log(messageString);
}
Console log
I am here--------------------------------------------->1
The folder23545 was removed from the workspace #workspace_name by #user_name
I am here--------------------------------------------->1
The folder23545 was removed from the workspace127 by #user_name
The above code replaces only 2 instances and sometimes eats up white space also as you can see at workspace127. What am i doing wrong?
Share Improve this question asked Jan 14, 2014 at 14:31 lal_bosdilal_bosdi 1733 silver badges13 bronze badges 2- What is the point of that lookahead? – tenub Commented Jan 14, 2014 at 14:39
- Just use thg435's solution. It makes the most sense to me. – tenub Commented Jan 14, 2014 at 14:47
2 Answers
Reset to default 6I guess replace
will be more suitable here:
result = messageString.replace(/#(\w+)/g, function(_, $1) { return extra_data[$1] })
or, to replace only words that start with #
:
.replace(/(^|\W)#(\w+)/g, function(_, $1, $2) { return $1 + extra_data[$2] })
- You are changing the string inside the loop.
re.exec
uses alastIndex
attribute to store where to start the next match. When you replace "#workspace_name" with "127",messageString
gets shorter. - You are consuming space at the beginning.
I think this should do it:
var messageString = "The folder #folder_name was removed from the workspace #workspace_name by #user_name"
var re = /(^|\W)#(\w+)/g, match;
var changedString = messageString;
while (match = re.exec(messageString)) {
changedString = changedString.replace(match[0], match[1] + extra_data[match[2]]);
}