0

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

2 Answers 2

1

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_]

Sign up to request clarification or add additional context in comments.

Comments

1

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.

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.