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?
The Solution. You can use str. replace(/ /g, "-") or str.
Use the replaceAll() method to replace spaces with dashes in a string, e.g. str. replaceAll(' ', '-') . The replaceAll method will return a new string where all spaces are replaced by dashes.
The $. trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With