admin管理员组

文章数量:1193328

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

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

I want to remove // plus all after the 2 slashes.

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

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

I want to remove // plus all after the 2 slashes.

Share Improve this question asked Nov 7, 2010 at 20:35 dr jerrydr jerry 10k25 gold badges83 silver badges127 bronze badges 2
  • Problem is with pathCode being multiline. I expected the $ to match on newline (\n), with the g flag set. So my question becomes: – dr jerry Commented Nov 8, 2010 at 7:38
  • How can remove the comments for each line separated by a newline (including the last line, optionally not ending with a new line). – dr jerry Commented Nov 8, 2010 at 7:40
Add a comment  | 

3 Answers 3

Reset to default 15

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 is equivalent to the regular-expression generated by your use of the RegExp object. In this case, using the literal is less verbose and might be preferable.

Are you reassigning the return value of replace into pathCode?

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

replace doesn't modify the string object that it works on. Instead, it returns a value.

This works fine for me:

var str = "abc//test";
str = str.replace(/\/\/.*$/g, '');

alert( str ); // alerts abc
a = a.replace(/\/\/.*$/, "");

本文标签: match end of line javascript regexStack Overflow