2010-07-09 56 views
80
var textTitle = "this is a test" 
var result = textTitle.replace(' ', '%20'); 

但替換功能停靠在「」的第一個實例,我也得到了的JavaScript .replace只替換第一個匹配

結果:"this%20is a test"

在哪裏,我要去錯我確信任何想法它是一個簡單的修復。

+5

在這種情況下,替換()是一個JavaScript字符串方法。沒有涉及jQuery。 – ajm 2010-07-09 17:03:35

+6

+1不使用jQuery – 2010-08-18 20:08:30

+0

[在JavaScript中替換所有出現的字符串]的可能重複(http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript) – chharvey 2016-07-25 02:24:25

回答

143

你需要一個/g在那裏,就像這樣:

var textTitle = "this is a test"; 
var result = textTitle.replace(/ /g, '%20'); 

You can play with it here,默認.replace()行爲是僅更換第一場比賽,the /g modifier(全球)告訴它全部替換。

+2

確實需要什麼。謝謝。 – Yardstermister 2010-07-12 08:17:15

+0

要更換管道,請參見[this](http://stackoverflow.com/questions/7795749/replace-pipe-and-comma-with-regex-in-javascript)。 – craned 2015-12-16 17:46:10

-3

嘗試使用replaceWith()replaceAll()

http://api.jquery.com/replaceAll/

+0

...誰高舉這個? – 2010-07-09 17:04:17

+1

他沒有問過一個JQuery版本嗎?我沒有在JQuery API中看到.replace() - 這就是vanilla Javascript。 – amfeng 2010-07-09 17:05:22

+2

@尼克你嫉妒或什麼? :) – 2010-07-09 17:05:32

6
textTitle.replace(/ /g, '%20'); 
1

From w3schools

一個子字符串(或正則表達式)之間的匹配和一個字符串的替換()方法檢索,並用新的子字符串替換匹配的子字符串

會更好地在這裏使用正則表達式,則:使用正則表達式,而不是第一個參數字符串

textTitle.replace(/ /g, '%20'); 
+0

感謝您的參考,它不是一個簡單的例子,以空白爲替代值(例如//g)。 – TheEmirOfGroofunkistan 2012-10-29 13:55:32

3

嘗試。

"this is a test".replace(/ /g,'%20') //#=> 「這個%圖20是%20A%20test」