Javascript regex line ending match

I'm probably doing something very stupid, but I can't get regexp to work in Javascript:

pathCode.replace(new RegExp("\/\/.*$","g"), ""); 

I want to delete // plus everything after two slashes.

+7
javascript regex
source share
3 answers

Seems to work for me:

 var str = "something //here is something more"; console.log(str.replace(new RegExp("\/\/.*$","g"), "")); // console.log(str.replace(/\/\/.*$/g, "")); will also work 

Also note that the regular expression literal /\/\/.*$/g equivalent to the regular expression generated by your use of the RegExp object. In this case, using the literal is less verbose and may be preferable.

Are you reassigning the return value of replace to pathCode ?

 pathCode = pathCode.replace(new RegExp("\/\/.*$","g"), ""); 

replace does not change the string object it is working on. Instead, it returns a value.

+10
source share

This works fine for me:

 var str = "abc//test"; str = str.replace(/\/\/.*$/g, ''); alert( str ); // alerts abc 
+2
source share
 a = a.replace(/\/\/.*$/, ""); 
+1
source share

All Articles