. Advertisement .
. Advertisement .
- Use the ReplaceAll() function
- Use the Replace() function
- Combine split() and join() function
Let’s learn the steps of each method!
Method 1: Use the ReplaceAll() function
This is the fastest, simplest and most widely used method. The replaceAll() method is used to return a new string after replacing the replacement characters that match the passed regular expression.
replaceAll(String regex, String replacement)
- String regex is the string that needs to be replaced
- String replacement is the string to be replaced.
const str = 'a-b-c'; const hyphensRemoved = str.replaceAll('-', ''); console.log(hyphensRemoved);
In the above program, to remove all hyphens, we just need to enter the value for String regex as ‘-‘, the value for String replacement as ”. And the result returned is the string after the hyphen has been removed.
Method 2: Use the Replace() function
Similar to the above method, Replace() also returns the string after it has been replaced.
String replace(char oldChar, char newChar)
- char oldChar is the old string that needs to be replaced
- char newChar is the new character string to replace
const str = 'a-b-c'; const hyphensRemoved = str.replace(/-/g, ''); console.log(hyphensRemoved);
Thus, by replacing all hyphens with spaces, the string has all hyphens removed.
Method 3: Combine split() and join() function
To put it simply, this method will be a combination of the split() function that splits the string and the join() function that joins, from which the function returns a new string.
To make it easier for you to visualize, we will give an example below:
const givenStr = '123-hello-ITtutoria'; const str = givenStr.split('-').join(''); console.log(str);
In the above example, the Split() function used a hyphen as a parameter to split the string into arrays, and the join() function joined the array, so the hyphen was removed.