user3146425
user3146425

Reputation: 23

Regex not replacing slash in string

I have just created a string that should replace a word starting with #. I succeed in doing that but as soon as i add slash after # in the string, it does replace it. This is my code

 <script>
var messageString = "The folder #/folder_name was removed from the workspace #workspace_name by #user_name"
result = messageString.replace(/#(\w+)/g, function(_, $1) { return " HELLO"; })
alert(result );
</script>

My question is why its not working when i add a slash after the # and how can i replace the word which has / also. Thanks in advance

Upvotes: 0

Views: 186

Answers (2)

Dalorzo
Dalorzo

Reputation: 20024

You need to include the slash as part of the valid characters to match, one way is to use [\/] along with the rest of the characters, will look like:

messageString.replace(/#([\/\w]+)/g,

Keep in mind that \w means [a-zA-Z_]

For example [\/\w]+ is equal too [\/a-zA-Z_]

Upvotes: 1

anubhava
anubhava

Reputation: 786359

You can use:

result = messageString.replace(/#(\S+)/g, function(_, $1) { return " HELLO"; })

\w is a word character that doesn't match / hence your regex is failing. \S, in contrast will match any non-space character.

Upvotes: 1

Related Questions