簡體   English   中英

替換字符串中的所有子字符串

[英]replace all substrings in strings

假設我有以下字符串:

var str = "The quick brown fox jumped over the lazy dog and fell into St-John's river";

我如何(使用jQuery或Javascript),在該字符串中替換子串(“the”,“over”,“and”,“into”,“s”),使用下划線,而不必調用str.replace(“”,“”)多次?

注意:我必須找出我要替換的子字符串是否被空格包圍。

謝謝

嘗試使用以下內容:

var newString = str.replace(/\b(the|over|and|into)\b/gi, '_');
// gives the output:
// _ quick brown fox jumped _ _ lazy dog _ fell _ St-John's river

\\b匹配單詞邊界, | 是'或',所以它'匹配''但它與'主題'中的字符不匹配。

/gi標志為G全球(所以它會取代所有匹配的出現次數。在i是區分大小寫的匹配,所以它會匹配thetHeTHE ...

用這個。

str = str.replace(/\b(the|over|and|into)\b/gi, '_');

使用帶有g標志的正則表達式,它將替換所有出現的情況:

var str = "The quick brown fox jumped over the lazy dog and fell into the river";
str = str.replace(/\b(the|over|and|into)\b/g, "_")
alert(str)  // The quick brown fox jumped _ _ lazy dog _ fell _ _ river

使用正則表達式。

str.replace(/(?:the|over|and|into)/g, '_');

?:不是絕對必要的,但是通過不捕獲匹配使命令稍微更高效。 g標志是全局匹配所必需的,因此將替換字符串中的所有出現。

我不確定你的意思是必須找出子串是否被空格包圍。 也許你的意思是你只想替換單個單詞,並保持空白完好無損? 如果是這樣,請使用它。

str.replace(/(\s+)(?:the|over|and|into)(\s+)/g, '$1_$2');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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