jQuery 替换单词中的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4932898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:12:20  来源:igfitidea点击:

jQuery replace spaces in word

jquery

提问by Jamie Taylor

I have an selecton my page with the valueof Test One

我有一个select我的页面上valueTest One

<option value="Test One">Test One</option>

<option value="Test One">Test One</option>

I wondered if there was a way to replace spaces in words using jQuery

我想知道是否有办法使用 jQuery 替换单词中的空格

I'm aware of the jQuery Trim technique but this only gets rid of spaces at the beginning and end and i'm looking for something to remove the spaces so it becomes TestOne

我知道 jQuery Trim 技术,但这只会去掉开头和结尾的空格,我正在寻找一些东西来删除空格,这样它就变成了 TestOne

Any ideas?

有任何想法吗?

回答by David Tang

A simple string.replacewill do the trick:

一个简单的方法string.replace就可以解决问题:

var str = "Test One";
str = str.replace(/ /g, '');

Now with regards to your question, this is where it gets a little confusing. If you want to replace the value attribute, then:

现在关于你的问题,这就是它变得有点混乱的地方。如果要替换value 属性,则:

$('option').val(function (i, value) {
    return value.replace(/ /g, '');
});

If you want to replace the text between the tags, then:

如果要替换标签之间的文本,则:

$('option').text(function (i, text) {
    return text.replace(/ /g, '');
});

回答by Kobi

To remove all spaces:

删除所有空格:

var str = $(selector).val();
str = str.replace(/\s+/g, '');

In JavaScript replaceonly catches the firstspace, so to replace more you need a tiny regular expression. If you're only expecting a single space or none, replace(' ', '')should work well.

在 JavaScript 中replace只捕获第一个空格,因此要替换更多空格,您需要一个很小的正则表达式。如果您只希望有一个空间或没有空间,replace(' ', '')应该会很好用。