replace() will only replace the first instance.
var str = "foo gar gaz"; // returns: "foo bar gaz" str.replace('g', 'b'); // returns: "foo bar baz" str = str.replace(/g/gi, 'b');
In the latter example, the trailing
/gi indicates case-insensitivity and global replacement (meaning that not just the first instance should be replaced), which is what you typically want when you're replacing in strings.
To remove characters, use an empty string as the replacement:
var str = "foo bar baz"; // returns: "foo r z" str.replace(/ba/gi, '');
Another method that no one has talked about so far is the substr method to produce strings out of another string...this is useful if your string has defined length and the characters your removing are on either end of the string...or within some "static dimension" of the string.
ONELINER which remove characters LIST (more than one at once) - for example remove
+,-, ,(,) from telephone number:
var str = "+(48) 123-456-789".replace(/[-+()\s]/g, ''); // result: "48123456789"
We use regular expression
[-+()\s] where we put unwanted characters between
\s" is 'space' character escape - for more info google 'character escapes in in regexp')
I know this is old but if you do a split then join it will remove all occurrences of a particular character ie:
var str = theText.split('A').join('')
will remove all occurrences of 'A' from the string, obviously it's not case sensitive
You can use replace function.
©2020 All rights reserved.