![](/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.