开发者

jQuery replace spaces in word

I have an select on my 开发者_运维百科page with the value of Test One

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

I wondered if there was a way to replace spaces in words using 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

Any ideas?


A simple string.replace will do the trick:

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:

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


To remove all spaces:

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜