我试图使用这段代码将空格替换为“_”,它适用于字符串中的第一个空格,但所有其他空格实例仍然保持不变。有人知道为什么吗?
function updateKey()
{
var key=$("#title").val();
key=key.replace(" ","_");
$("#url_key").val(key);
}
我试图使用这段代码将空格替换为“_”,它适用于字符串中的第一个空格,但所有其他空格实例仍然保持不变。有人知道为什么吗?
function updateKey()
{
var key=$("#title").val();
key=key.replace(" ","_");
$("#url_key").val(key);
}
尝试使用.replace(/ /g,"_");
编辑: 如果您不喜欢正则表达式,也可以使用.split(' ').join('_')
编辑: John Resig说过:
如果您正在对具有静态搜索和静态替换的字符串执行搜索和替换,则使用 .split("match").join("replace") 执行操作速度更快 - 这似乎违反直觉,但在大多数现代浏览器中它能够这样工作。 (下一版本的Firefox中存在改进.replace(/match/g, "replace")性能的变化 - 因此以前的说法不会再长时间存在。)
回答Prasanna在下面提出的问题:
如何在JavaScript中将多个空格替换为单个空格?
您将使用相同的replace
函数,但使用不同的正则表达式。空白的表达式是\s
,而“1次或更多次”的表达式是+
加号,因此您只需用以下内容替换Adam的回答:
key=key.replace(/\s+/g,"_");
你可以试试这个
var str = 'hello world !!';
str = str.replace(/\s+/g, '-');
它甚至将多个空格替换为单个“-”。
用下划线替换空格
var str = 'How are you';
var replaced = str.split(' ').join('_');
输出:你好吗
我为此创建了JS性能测试http://jsperf.com/split-and-join-vs-replace2
。之所以会发生这种情况,是因为replace()
方法是这样设计的,当您使用字符串查找匹配时,它只替换第一个匹配项。请检查replace方法。
要替换所有匹配项,可以使用以下 3 种方法:
replace()
method:When you use the replace
method with regex with /g
flag it replaces all the matching occurrences in a string.
function updateKey()
{
var key=$("#title").val();
key=key.replace(/ /g,"_");
$("#url_key").val(key);
}
// Show case
let title = "Your document title";
console.log(title.replace(/ /g,"_"));
The replaceAll
method will remove all spaces with an underscore. (must use the global flag with it
when using regex)
function updateKey()
{
var key=$("#title").val();
key=key.replaceAll(/ /g,"_");
// key=key.replaceAll(" ","_"); also valid
$("#url_key").val(key);
}
// Show case
let title = "Your document title";
console.log(title.replaceAll(/ /g,"_"));
split
and join
method:Split your string at spaces and join it by using _ as a separator in the join method.
function updateKey()
{
var key=$("#title").val();
key=key.split(" ").join("_");
$("#url_key").val(key);
}
// Show case
let title = "Your document title";
console.log(title.split(" ").join("_"));
Just using replace
:
var text = 'Hello World';
new_text = text.replaceAll(' ', '_');
console.log(new_text);
我知道这已经过时了,但是我没有看到有人提到扩展字符串prototype
。
String.prototype.replaceAll = function(search, replace){
if(!search || !replace){return this;} //if search entry or replace entry empty return the string
return this.replace(new RegExp('[' + search + ']', 'g'), replace); //global RegEx search for all instances ("g") of your search entry and replace them all.
};
const updateKey = key => console.log(key.split(' ').join('_'));
updateKey('Hello World');
/\ /g
来代替/ /g
。两者都是可行的方法。而在CoffeeScript中只有后者有效。 - Tom Leys.replace(/ /g,"_");
比.split(' ').join('_')
更快。 - Gabriel Tomitsuka