Sometimes, we want to trim a specific character from a string with JavaScript.
In this article, we’ll look at how to trim a specific character from a string with JavaScript.
Use the String.prototype.replace Method
We can use the JavaScript string’s replace
method to remove all instances of a given character.
To use it, we write:
const x = '|f|oo||';
const y = x.replace(/^|+||+$/g, '');
console.log(y);
We have the string x
that we want to remove the ||
substrings from,
Then we call x.replace
with a regex that matches the ||
substring in x
to replace them.
The g
flag matches all instances of a given pattern.
The 2nd argument we pass into replace
is an empty string so we remove all instances of the substring that matches the pattern in the first argument.
Therefore, y
is 'f|oo’
.
Use the String.prototype.replaceAll Method
We can do the same thing with the JavaScript string replaceAll
method that comes with ES2021.
For instance, we can write:
const x = '|f|oo||';
const y = x.replaceAll(/^|+||+$/g, '');
console.log(y);
to replace replace
with replaceAll
.
The regex we pass in must have the g
flag or we’ll get an error since it can only replace all substrings that match the given pattern.
And so we get the same result as the previous example.
Conclusion
We can use the JavaScript string replace
or replaceAll
method to remove all substrings that match the given pattern.