2011-05-03 89 views
5

假設我有一個可變該字符串的長度是不固定的,有時會像找到一個子串和插入另一個字符串

var a = xxxxxxxxhelloxxxxxxxx; 

有時像

var a = xxxxhelloxxxx; 

我不能使用substr()因爲位置不一樣。

如何在字符串中找到字符串「hello」並在「hello」後插入字符串「world」? (在JavaScript或jQuery的方法被歡迎)

由於

回答

15

var a = "xxxxhelloxxxxhelloxxxx"; 
 
a = a.replace(/hello/g,"hello world"); // if you want all the "hello"'s in the string to be replaced 
 
document.getElementById("regex").textContent = a; 
 

 
a = "xxxxhelloxxxxhelloxxxx"; 
 
a = a.replace("hello","hello world"); // if you want only the first occurrence of "hello" to be replaced 
 
document.getElementById("string").textContent = a;
<p>With regex: <strong id="regex"></strong></p> 
 
<p>With string: <strong id="string"></strong></p>

+2

Replace會返回一個新的字符串,所以您需要將其分配回 – 2011-05-03 05:10:50

1
var find = "hello"; 

var a = "xxxxxxxxxxxxxhelloxxxxxxxxxxxxxxxx"; 
var i = a.indexOf(find); 

var result = a.substr(0, i+find.length) + "world" + a.substr(i+find.length); 

alert(result); //xxxxxxxxxxxxxhelloworldxxxxxxxxxxxxxxxx 

也許。

4

這將替換第一次出現

a = a.replace("hello", "helloworld"); 

如果您需要更換所有出現的,你需要一個正則表達式。 (結尾處的g標誌的意思是「全球性」,所以它會找到所有出現。)

a = a.replace(/hello/g, "helloworld"); 
+2

+1,但這隻會替換第一個找到的實例。 – 2011-05-03 05:11:51

1

您可以使用替換,會比的indexOf

var newstring = a.replace("hello", "hello world"); 
3

這將替換第一個要容易得多次數:

a = a.replace("hello", "hello world"); 

如果您需要更換所有出現,您使用的匹配正則表達式,並使用全球(G)標誌:

a = a.replace(/hello/g, "hello world"); 
+0

第一個拼寫錯誤。 'repalce'。 – user2072826 2015-07-15 18:06:09

+0

@ user2072826:感謝您的發現。 – Guffa 2015-07-15 20:02:58

相關問題