Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript regex with escaped slashes does not replace

Do i have to escape slashes when putting them into regular expression?

myString = '/courses/test/user'; myString.replace(/\/courses\/([^\/]*)\/.*/, "$1"); document.write(myString); 

Instead of printing "test", it prints the whole source string.

See this demo:

http://jsbin.com/esaro3/2/edit

like image 793
Radek Simko Avatar asked Jan 12 '11 21:01

Radek Simko


1 Answers

Your regex is perfect, and yes, you must escape slashes since JavaScript uses the slashes to indicate regexes.

However, the problem is that JavaScript's replace method does not perform an in-place replace. That is, it does not actually change the string -- it just gives you the result of the replace.

Try this:

myString = '/courses/test/user'; myString = myString.replace(/\/courses\/([^\/]*)\/.*/, "$1"); document.write(myString); 

This sets myString to the replaced value.

like image 114
Reid Avatar answered Sep 21 '22 17:09

Reid