Very simple little question, but I don't quite understand how to do it.
I need to replace every instance of '_' with a space, and every instance of '#' with nothing/empty.
var string = '#Please send_an_information_pack_to_the_following_address:';
I've tried this:
string.replace('#','').replace('_', ' ');
I don't really chaining commands like this, but is there another way to do it in one?
Use the OR operator (
|
):You could also use a character class:
Fiddle
If you want to replace the hash with one thing and the underscore with another, then you will just have to chain. However, you could add a prototype:
Why not chain, though? I see nothing wrong with that.
Chaining is cool, why dismiss it?
Anyway, here is another option in one replace:
The replace will choose "" if match=="#", " " if not.
[Update] For a more generic solution, you could store your replacement strings in an object:
If you want to replace multiple characters you can call the
String.prototype.replace()
with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping which you will use in that function.For example, if you want
a
replaced withx
,b
withy
andc
withz
, you can do something like this:Output:
234xyz567yyyyxz
Specify the
/g
(global) flag on the regular expression to replace all matches instead of just the first:To replace one character with one thing and a different character with something else, you can't really get around needing two separate calls to
replace
. You can abstract it into a function as Doorknob did, though I would probably have it take an object with old/new as key/value pairs instead of a flat array.You could also try this :
find
refers to the text to be found andreplace
to the text to be replaced withThis will be replacing case insensitive characters. To do otherway just change the Regex flags as required. Eg: for case sensitive replace :
You can also pass a RegExp object to the replace method like
Javascript RegExp