dr jerry
dr jerry

Reputation: 10026

match end of line javascript regex

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.

Upvotes: 10

Views: 29161

Answers (3)

Steve Claridge
Steve Claridge

Reputation: 11080

a = a.replace(/\/\/.*$/, "");

Upvotes: 1

Vivin Paliath
Vivin Paliath

Reputation: 95488

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.

Upvotes: 15

Harmen
Harmen

Reputation: 22438

This works fine for me:

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

alert( str ); // alerts abc

Upvotes: 4

Related Questions