Javascript 替换正则表达式通配符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4225577/
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-08-23 11:28:20  来源:igfitidea点击:

Javascript replace regex wildcard

javascriptregex

提问by Kristian

I have a string which I need to run a replace.

我有一个需要运行替换的字符串。

string = replace('/blogs/1/2/all-blogs/','');

The values 1, 2 and all-blogs can change. Is it possible to make them wildcards?

值 1、2 和 all-blogs 可以更改。是否可以使它们成为通配符?

Thanks in advance,

提前致谢,

Regards

问候

回答by T.J. Crowder

You can use .*as a placeholder for "zero or more of any character here" or .+for "one or more of any character here". I'm not 100% sure exactly what you're trying to do, but for instance:

您可以.*用作“此处有零个或多个任何字符”或.+“此处有一个或多个任何字符”的占位符。我不是 100% 确定你想要做什么,但例如:

var str = "/blogs/1/2/all-blogs/";
str = str.replace(/\/blogs\/.+\/.+\/.+\//, '');
alert(str); // Alerts "", the string is now blank

But if there's more after or before it:

但如果在它之后或之前还有更多:

str = "foo/blogs/1/2/all-blogs/bar";
str = str.replace(/\/blogs\/.+\/.+\/.+\//, '');
alert(str); // Alerts "foobar"

Live example

活生生的例子

Note that in both of the above, only the firstmatch will be replaced. If you wanted to replace allmatches, add a glike this:

请注意,在以上两个中,只会替换第一个匹配项。如果要替换所有匹配项,请添加g如下内容:

str = str.replace(/\/blogs\/.+\/.+\/.+\//g, '');
//                                       ^-- here

You can read up on JavaScript's regular expressions on MDC.

您可以在 MDC上阅读 JavaScript 的正则表达式

回答by ThiefMaster

js> 'www.google.de/blogs/1/2/all-blogs'.replace(/\/blogs\/[^\/]+\/[^\/]+\/[^\/]+\/?/, '');
www.google.de

回答by Klemen Slavi?

What about just splitting the string at slashes and just replacing the values?

仅在斜杠处拆分字符串并仅替换值怎么样?

var myURL = '/blogs/1/2/all-blogs/', fragments, newURL;
fragments = myURL.split('/');
fragments[1] = 3;
fragments[2] = 8;
fragments[3] = 'some-specific-blog';
newURL = fragments.join('/');

That should return:

那应该返回:

'/blogs/3/8/some-specific-blog'

回答by Keng

Try this

尝试这个

(/.+){4}

escape as appropriate

适当逃脱