gpt4 book ai didi

javascript - 在 JavaScript 中用下划线替换空格?

转载 作者:IT老高 更新时间:2023-10-28 11:04:51 26 4
gpt4 key购买 nike

我正在尝试使用此代码将空格替换为 _,它适用于字符串中的第一个空格,但所有其他空格实例保持不变。有人知道为什么吗?

function updateKey()
{
var key=$("#title").val();
key=key.replace(" ","_");
$("#url_key").val(key);
}

最佳答案

试试.replace(//g,"_");

编辑:或 .split(' ').join('_') 如果你厌恶 REs

编辑:John Resig said :

If you're searching and replacing through a string with a static search and a static replace it's faster to perform the action with .split("match").join("replace") - which seems counter-intuitive but it manages to work that way in most modern browsers. (There are changes going in place to grossly improve the performance of .replace(/match/g, "replace") in the next version of Firefox - so the previous statement won't be the case for long.)

关于javascript - 在 JavaScript 中用下划线替换空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/441018/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com