Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
7
rated 0 times [  12] [ 5]  / answers: 1 / hits: 88037  / 14 Years ago, wed, january 12, 2011, 12:00:00

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


More From » regex

 Answers
46

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.


[#94246] Tuesday, January 11, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pranavrorys

Total Points: 466
Total Questions: 87
Total Answers: 115

Location: Barbados
Member since Sun, Nov 27, 2022
2 Years ago
pranavrorys questions
Fri, May 27, 22, 00:00, 2 Years ago
Thu, Oct 28, 21, 00:00, 3 Years ago
Sat, May 30, 20, 00:00, 4 Years ago
Fri, Dec 20, 19, 00:00, 5 Years ago
;