I need to take a user input, in this case as a search word. But when sending this input to an API, the string must not contain any spaces. I tried .trim but this seems to only remove any spaces before and/or after the string. Essentially, I need to force any amount of words other than one together, any thoughts on how this could be achieved would be greatly appreciated.
function getSearch(){
var welcomeMsg = document.getElementById('result');
var search_term = document.getElementById('floatingInput');
<input type="text" id="floatingInput">
<input type="button" value="click">
<label for="floatingInput">Song title / artist name</label>
CodePudding user response:
You can use String.prototype.replace()
for this, for example:
> 'foo bar'.replace(' ', '')
'foobar'
If there are expected to be many spaces, you can use a global regular expression:
> 'foo bar baz otherfoo'.replace(/ /g, '')
'foobarbazotherfoo'
Finally, if you still want to see the word boundaries as suggested by @JoeKincognito, you can update the second argument from an empty space ''
to the separator of your choice, for example:
> 'foo bar baz otherfoo'.replace(/ /g, '-')
'foo-bar-baz-otherfoo'
This will allow you to separate the search terms later if necessary, and will allow you to differentiate between users searching for e.g., butter
and fingers
from users searching for butterfingers
CodePudding user response:
string.replace()
method supports regex expression:
xxx.replace(/\s /g, '') //xxx is an example string.
\s: matches any whitespace symbol
CodePudding user response:
your_search_term.replace(/ /g,'');