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 no
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.
Specify the /g
(global) flag on the regular expression to replace all matches instead of just the first:
string.replace(/_/g, ' ').replace(/#/g, '')
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.
String.prototype.replaceAll=function(obj,keydata='key'){
const keys=keydata.split('key');
return Object.entries(obj).reduce((a,[key,val])=> a.replace(new RegExp(`${keys[0]}${key}${keys[1]}`,'g'),val),this)
}
const data='hids dv sdc sd {yathin} {ok}'
console.log(data.replaceAll({yathin:12,ok:'hi'},'{key}'))
String.prototype.replaceAll=function(keydata,obj){
const keys=keydata.split('key');
return Object.entries(obj).reduce((a,[key,val])=> a.replace(${keys[0]}${key}${keys[1]}
,val),this)
}
const data='hids dv sdc sd ${yathin} ${ok}' console.log(data.replaceAll('${key}',{yathin:12,ok:'hi'}))
For replacing with nothing, tckmn's answer is the best.
If you need to replace with specific strings corresponding to the matches, here's a variation on Voicu's and Christophe's answers that avoids duplicating what's being matched, so that you don't have to remember to add new matches in two places:
const replacements = {
'’': "'",
'“': '"',
'”': '"',
'—': '---',
'–': '--',
};
const replacement_regex = new RegExp(Object
.keys(replacements)
// escape any regex literals found in the replacement keys:
.map(e => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('|')
, 'g');
return text.replace(replacement_regex, e => replacements[e]);
Chaining is cool, why dismiss it?
Anyway, here is another option in one replace:
string.replace(/#|_/g,function(match) {return (match=="#")?"":" ";})
The replace will choose "" if match=="#", " " if not.
[Update] For a more generic solution, you could store your replacement strings in an object:
var replaceChars={ "#":"" , "_":" " };
string.replace(/#|_/g,function(match) {return replaceChars[match];})
yourstring = '#Please send_an_information_pack_to_the_following_address:';
replace '#' with '' and replace '_' with a space
var newstring1 = yourstring.split('#').join('');
var newstring2 = newstring1.split('_').join(' ');
newstring2 is your result