jQuery replace spaces in word

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.


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

Tags:

Jquery