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 like chaining commands like this. Is there another way to do it in one?
Use the replace() method to replace multiple characters in a string, e.g. str. replace(/[. _-]/g, ' ') . The first parameter the method takes is a regular expression that can match multiple characters.
You can replace many in one line: string. replace(/[#_]/g, x => ({'_': ' ', '#': ''})[x]); Note the () around the object — it will error without them.
SELECT REPLACE(REPLACE(REPLACE(REPLACE('3*[4+5]/{6-8}', '[', '('), ']', ')'), '{', '('), '}', ')'); We can see that the REPLACE function is nested and it is called multiple times to replace the corresponding string as per the defined positional values within the SQL REPLACE function.
To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')
Use the OR operator (|
):
var str = '#this #is__ __#a test###__'; str.replace(/#|_/g,''); // result: "this is a test"
You could also use a character class:
str.replace(/[#_]/g,'');
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:
String.prototype.allReplace = function(obj) { var retStr = this; for (var x in obj) { retStr = retStr.replace(new RegExp(x, 'g'), obj[x]); } return retStr; }; console.log('aabbaabbcc'.allReplace({'a': 'h', 'b': 'o'})); // console.log 'hhoohhoocc';
Why not chain, though? I see nothing wrong with that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With