Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery replace spaces in word

Tags:

jquery

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?

like image 569
Jamie Taylor Avatar asked Feb 08 '11 12:02

Jamie Taylor


People also ask

How to replace into space in JQuery?

The Solution. You can use str. replace(/ /g, "-") or str.

How to replace space with hyphen in JQuery?

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.

How to remove space from Text in JQuery?

The $. trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string.


2 Answers

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, '');
});
like image 54
David Tang Avatar answered Oct 16 '22 11:10

David Tang


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.

like image 14
Kobi Avatar answered Oct 16 '22 10:10

Kobi