In general, a string is define as a sequence of characters in a programming language. It can be a word or a sentence.
It return us a new string with the replaced word.
As per the definition, the replace() method is use to replace character, however we can also use it to remove character in a string too.
We just have to change the replaceCharacter to an empty string ('').
Lets see it in action:
let text = 'I have a cat'; // search word is 'a' and replace Character is empty string ' ' let removeChar = text.replace('a', ''); console.log(removeChar);
I hve a cat
As you can see in the output, the
replace() have only replace the first occurrence of the character 'a' in the string. This is because replace() method stops the search at the first occurrence of the character and do not continue the search afterwards.
Remove Character From a String Using Regular Expression
So to solve this issue, we will have to use the regular expression with the
Lets see an example:
let text = 'I have a cat'; // search word is /a/g (regular expression) and replace Character is empty string ' ' let removeChar = text.replace(/a/g, ''); console.log(removeChar);
I hve ct
When we use a regular expression with the
g modifier, it check for the searchCharacter (here the character a) in the whole string and remove all the occurrence of the character.
split() method truncate (divide) a string into substrings depending on its splitter ( divider ). And a splitter can be just a character or a regular expression.
After splitting the string , it returns us an array with the substrings.
let text = 'I have a cat'; // split the string with splitter as letter 'a' let removeChar = text.split('a'); console.log(removeChar); // [ 'I h', 've ', ' c', 't' ]
let array = ['one','two','three'] let joinArr = array.join("+") console.log(joinArr) // one+two+three
So, now using the
join method, we can remove character in a string using split() method and then join it together using join() method with an empty string ('') in join as a separator.
We will remove the character 'a' from the string ('I have a cat')
let text = 'I have a cat'; // split the string with splitter as letter 'a' and join it with and empty string ("") let removeChar = text.split('a').join('') console.log(removeChar);
I hve ct