Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple characters in one replace call

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?

like image 802
Shannon Hochkins Avatar asked May 16 '13 00:05

Shannon Hochkins


People also ask

How do I replace multiple characters in a string?

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.

How can I replace multiple characters in a string using jquery?

You can replace many in one line: string. replace(/[#_]/g, x => ({'_': ' ', '#': ''})[x]); Note the () around the object — it will error without them.

How do I replace multiple characters in SQL?

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.

Can you replace all occurrences?

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')


1 Answers

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,''); 

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:

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.

like image 122
tckmn Avatar answered Oct 16 '22 23:10

tckmn