Method 1: Using split() and join() Method.
The split() method is used to split a string into multiple sub-strings and return them in the form of an array. A separator can be specified as a parameter so that the string is split whenever that separator is found in the string. The space character (” “) is specified in this parameter to separate the string whenever a space occurs. The join() method is used to join an array of strings using a separator. This will return a new string with the joined string using the specified separator. This method is used on the returned array and no separator (“”) is used to join the strings. This will join the strings in the array and return a new string. This will remove all the spaces in the original string.
Method 2: Using replace() method with regex.
The replace() method is used to replace a specified string with another string. It takes two parameters, the first is the string to be replaced and the second parameter is the string replaced with. The second string can be given as an empty string so that the empty space to be replaced. The first parameter is given a regular expression with a space character (” “) along with the global property. This will select every occurrence of space in the string and it can then be removed by using an empty string in the second parameter. This will remove all the spaces in the original string.
string.replace(/ /g, "")
Method 3: Using reduce() method with spread operator.
The spread operator is used to convert the string to an array and The reduce() method is used to reduce the array to a single value and executes a provided function for each value of the array and the return value of the function is stored in an accumulator and form an single value from the array. Function check each character of string is space or not if it is space don’t add character to accumulator and if it not space then add character to accumulator. At the last accumulator return string which doesn’t contains any space in it.
[...string].reduce((accum, char)=> (char===" ") ? accum : accum + char, '')
Please Login to comment...