Jamie Taylor
Jamie Taylor

Reputation: 3530

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?

Upvotes: 10

Views: 62375

Answers (2)

Kobi
Kobi

Reputation: 138017

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.

Upvotes: 14

David Tang
David Tang

Reputation: 93674

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

Upvotes: 45

Related Questions