Javascript url.replace是否为多个替换?
我现在有以下方法来删除空格并用连字符替换它们。 如何用连字符替换空格,用零替换点,并将其保持在同一个变量中Javascript url.replace是否为多个替换?,javascript,jquery,Javascript,Jquery,我现在有以下方法来删除空格并用连字符替换它们。 如何用连字符替换空格,用零替换点,并将其保持在同一个变量中 url = url.replace(/\s/g, '-'); url=url.replace(/\s/g',-).replace(/\./g',)可能会这样做。url=url.replace(/\s/g,“-”).replace(/\./g,”)可能会这样做。我使用这个: // This little gadget does replace for all not just first
url = url.replace(/\s/g, '-');
url=url.replace(/\s/g',-).replace(/\./g',)
可能会这样做。url=url.replace(/\s/g,“-”).replace(/\./g,”)代码>可能会这样做。我使用这个:
// This little gadget does replace for all not just first occurence like the native javascript function.
String.prototype.replaceAll = function(strTarget, strSubString){
var strText = this;
var intIndexOfMatch = strText.indexOf(strTarget);
while (intIndexOfMatch != -1){
strText = strText.replace(strTarget, strSubString);
intIndexOfMatch = strText.indexOf(strTarget);
}
return(strText);
}
我用这个:
// This little gadget does replace for all not just first occurence like the native javascript function.
String.prototype.replaceAll = function(strTarget, strSubString){
var strText = this;
var intIndexOfMatch = strText.indexOf(strTarget);
while (intIndexOfMatch != -1){
strText = strText.replace(strTarget, strSubString);
intIndexOfMatch = strText.indexOf(strTarget);
}
return(strText);
}
对于基本空格和点,不需要使用正则表达式。只能说url.replace('''-')。replace('.''.','');好电话。我甚至没有想到这一点;只是复制了OPs代码并附加了。谢谢。@ReneGeuze您仍然需要g
来命中所有替换项。所以我们无论如何都需要一个正则表达式模式。是的,正如Jan回答的那样,这是正确的并且有效的。如何将替换为“”的(&a)添加到该列表中。它是否只是添加了另一个。替换(/\&/g')基本空格和点,不需要使用正则表达式。只能说url.replace('''-')。replace('.''.','');好电话。我甚至没有想到这一点;只是复制了OPs代码并附加了。谢谢。@ReneGeuze您仍然需要g
来命中所有替换项。所以我们无论如何都需要一个正则表达式模式。是的,正如Jan回答的那样,这是正确的并且有效的。如何将替换为“”的(&a)添加到该列表中。它是否只是添加了另一个.replace(/\&/g'')