Remove space from string in javascript
To remove spaces from a string in JavaScript, you can use various methods depending on your needs. Here are some common approaches:
1. Remove All Spaces
To remove all spaces (including spaces between words), you can use the replace
method with a regular expression:
2. Remove Leading and Trailing Spaces
To remove only leading and trailing spaces, use the trim
method:
3. Remove Only Spaces Between Words
To remove spaces between words but keep single spaces intact, you can use replace
with a regular expression:
Summary
Use
replace(/\s+/g, '')
to remove all spaces.Use
trim()
to remove leading and trailing spaces.Use
replace(/\s+/g, ' ').trim()
to condense multiple spaces between words into a single space.