3

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" class="form-control" id="floatingInput">
  <input type="button" value="click">
  <label for="floatingInput">Song title / artist name</label>

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

If you want to get it back to 2 words on the backend maybe replace with '_' instead of ''
2

string.replace() method supports regex expression:

xxx.replace(/\s+/g, '') //xxx is an example string.
\s: matches any whitespace symbol

1 Comment

Nice! I didn't think of using \s+. If you are just removing the spaces it will end up the same as replace(/ /g, ''), but if you are using a separator instead, I like that \s+ will dedupe extra spaces so that 'foo bar' would become e.g., 'foo-bar' instead of 'foo---bar'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.