sourlemonaid sourlemonaid - 5 months ago 23
Javascript Question

replace multiple different characters with different values javascript

I am trying to replace different set characters with corresponding values. for example every < to be replaced with a #U34 and every $ to replaced with )#89.

I have an array of strings that have those characters randomly thrown about. for example:

var arr = [

so far I figured out that i can do:

var replace = /</ig;
var newString = textWithCharacters.replace(replace, '#U34');

but this seems like it can only be done for one character at a time. and if i want to do more than one I seems like i need to create a new string each time. is there a way to do this in one go? maybe with a loop and if statements? but i can't seem to figure out how i would define the conditions of the loop.


the .replace() method accepts a function for the second argument that gets passed the matched string (e.g. '<'), and returns the replacement text (e.g. '#U34').

So, you can do something like this:

var replacementMap = {
  '<': '#U34',
  '$': ')#89'

// Create a RegExp to match any of the characters that are used as keys in the map.
// For this example, this RegExp is the same as /[<$]/gi
// Note: this method of creating a RegExp may not work with certain characters such
// as -, ], or \
var replace = new RegExp('[' + Object.keys(replacementMap).join('') + ']', 'ig');

function getReplacementString(input) {
  return replacementMap[input];

var newString = textWithCharacters.replace(replace, getReplacementString);