在JavaScript中用下划线替换空格? [英] Replacing spaces with underscores in JavaScript?

查看:95
本文介绍了在JavaScript中用下划线替换空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use this code to replace spaces with _, it works for the first space in the string but all the other instances of spaces remain unchanged. Anybody know why?

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


推荐答案

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

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

Edit: or .split(' ').join('_') if you have an aversion to REs

编辑 John Resig说


如果您正在搜索并通过带有静态搜索
的字符串替换
并将静态替换为
,请使用$ b $执行操作b .split(match)。join(replace) -
这似乎反直觉,但
设法在大多数
现代浏览器中以这种方式工作。 (在
Firefox的下一个版本中,有一些变化
可以大幅度提高.replace(/ match / g,
replace)的
性能 - 所以之前的陈述
不会长期存在。)

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中用下划线替换空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆