匹配行javascript regex的末尾

时间:2022-11-24 15:24:05

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

我可能在做一些非常愚蠢的事情,但是我不能按照regexp使用Javascript:

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

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

我想删除// +所有后的两个斜杠。

3 个解决方案

#1


10  

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.

还要注意,正则表达式的文字/\/\/。*$/g等于您使用RegExp对象生成的正则表达式。在这种情况下,使用文字比较不冗长,可能更好。

Are you reassigning the return value of replace into pathCode?

是否将replace的返回值重新分配到路径码?

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

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

replace不会修改它所使用的字符串对象。相反,它返回一个值。

#2


2  

This works fine for me:

这对我来说很好:

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

alert( str ); // alerts abc

#3


1  

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

#1


10  

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.

还要注意,正则表达式的文字/\/\/。*$/g等于您使用RegExp对象生成的正则表达式。在这种情况下,使用文字比较不冗长,可能更好。

Are you reassigning the return value of replace into pathCode?

是否将replace的返回值重新分配到路径码?

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

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

replace不会修改它所使用的字符串对象。相反,它返回一个值。

#2


2  

This works fine for me:

这对我来说很好:

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

alert( str ); // alerts abc

#3


1  

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