簡體   English   中英

正則表達式字符串替換

[英]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-');

另外,接受httphttps總是很好:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM