0

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?

2
  • What is the point of that lookahead? Commented Jan 14, 2014 at 14:39
  • Just use thg435's solution. It makes the most sense to me. Commented Jan 14, 2014 at 14:47

2 Answers 2

6

I 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] })
Sign up to request clarification or add additional context in comments.

1 Comment

I probably would have a check to make sure that there is a value. +1
1
  • You are changing the string inside the loop. re.exec uses a lastIndex 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]]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.