javascript 匹配行尾javascript正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4119556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:25:15  来源:igfitidea点击:

match end of line javascript regex

javascriptregex

提问by dr jerry

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

我可能正在做一些非常愚蠢的事情,但我无法在 Javascript 中使用以下正则表达式:

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

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

我想删除 // 加上 2 个斜线之后的所有内容。

回答by Vivin Paliath

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

另请注意,正则表达式文字/\/\/.*$/g等效于您使用RegExp对象生成的正则表达式。在这种情况下,使用文字不那么冗长,可能更可取。

Are you reassigning the return value of replaceinto pathCode?

您是否正在重新分配replaceinto的返回值pathCode

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

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

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

回答by Harmen

This works fine for me:

这对我来说很好用:

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

alert( str ); // alerts abc

回答by Steve Claridge

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