![](/img/trans.png)
[英]Is it necessary to escape the replacement string in a String.replace() call with a regular expression?
[英]regular expression string replacement
我有这样的网址:
http://mywebsite.com/my-very-long-product-title/my_sku,default,pd.html
我想将此字符串替换为
http://mywebsite.com/-/my_sku,default,pd.html
我只使用javascript。 规则是我要始终替换最靠近字符串末尾的单个斜杠之间的所有内容。
如果您始终要替换该完全相同的字符串,则可以执行以下操作:
new_string = old_string.replace(/my-very-long-product-title/, '-');
如果要替换mywebsite.com/
之后的内容,请执行以下操作:
new_string = old_string.replace(/(mywebsite.com\/)[^\/]+/, '$1-');
或者也许,要确保您不要替换诸如http://mywebsite.com/whatever/mywebsite.com/this-shouldnt-be-replaced/etc
类的字符串,请执行以下操作:
new_string = old_string.replace(/^(http:\/\/mywebsite.com\/)[^\/]+/, '$1-');
另外,接受http
和https
总是很好:
new_string = old_string.replace(/^(https?:\/\/mywebsite.com\/)[^\/]+/, '$1-');
要使用/-/
替换从倒数第二个斜杠到最后一个斜杠的所有内容,可以使用
result = subject.replace(/\/[^\/]*\/(?=[^\/]*$)/g, "/-/");
更具可读性:
/ # Slash
[^/]* # followed by any number of non-slash characters
/ # and another slash.
(?=[^/]*$) # Make sure that there is no further slash until the end of the string
编辑以匹配您的问题
好的,因为这是在正则表达式类别中,所以我将给出一个正则表达式答案:
var text = 'http://mywebsite.com/my-very-long-product-title/my_sku,default,pd.html';
var re = '/(http:\/\/.+\/)[^\/]+?(\/.+)/i';
text.replace(re,'$1-$2');
或者,您正在谈论要进行以下操作: http://mywebsite.com/-/my_sku,default,pd.html
加载与http://mywebsite.com/my-very-long-product-title/my_sku,default,pd.html
相同的数据http://mywebsite.com/my-very-long-product-title/my_sku,default,pd.html
吗? -因为这确实是一个非常不同的问题。
var oldUrl = "http://mywebsite.com/my-very-long-product-title/my_sku,default,pd.html";
var groups = /^(.*?com\/).*(\/.*)$/.exec(oldUrl);
var newUrl = groups[1] + "-" + groups[2];
另一个答案-像蒂姆·皮茨克(Tim Pietzcker)一样,不用先行。
find: /[^/]*(/[^/]*)$
replace: /-$1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.