jQuery替换单词中的空格 [英] jQuery replace spaces in word

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

问题描述

我的页面上有一个select,其中valueTest One

I have an select on my page with the value of Test One

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

我想知道是否存在一种使用jQuery替换单词中空格的方法

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

我知道jQuery Trim技术,但这只会消除开头和结尾的空格,我正在寻找一些东西来删除空格,使其变为TestOne

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

有什么想法吗?

推荐答案

简单的string.replace可以解决问题:

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

现在,关于您的问题,这里变得有些混乱.如果要替换 value属性,则:

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

$('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, '');
});

这篇关于jQuery替换单词中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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