replaceAll() returns a new string.
const originalStr = 'Hello John wick'; const withoutSpaceStr = originalStr.replaceAll(' ', '-'); console.log(withoutSpaceStr); // Hello-John-wick
While ReplaceAll() is perfect method to replace all spaces from string, you can also use s
tring.replace(' ',newcharacter) to replace only first occurrence of space.
If you want to remove all occurrences of space from string using string.replace() method, then you will have to use Regex.
originalString.replace(/ /g, '-');'
So, take a look at a complete example:
const originalStr = 'Hello John wick'; const withoutSpaceStr = originalStr.replace(/ /g, '-'); console.log(withoutSpaceStr); // Hello-John-wick
So, the output remains same as above example, but we are using Regex with .replace() to make the string remove all occurences of space.
.replace() arguments, we are passing 2 argument
- A regular expression that matches all spaces (The forward slashes / / mark the beginning and end of the regular expression.)
- Second argument is '-', replacement string/character for each regex match.
We replaced all spaces with a dash(-) in the above example. However, you could provide any replacement string.
You may also like to read: