Home > Mobile >  Replace a string with array values in javascript
Replace a string with array values in javascript

Time:11-15

I am trying to replace values of string with array values in javascript by joining the values of string with array values. for example:

my string is

var str = 'a*b-ab';
var arrayElement = [['a', 'class 1'], ['b', 'class 12'],['ab', 'class 15'],['ac', 'class 2']]

Now, string(str) has a, b, ab and array has a, b, ab, ac. we need to join string values like a, b, and ab and to get their description from array. and my output has to be

class 1 * class 12 - class 15

is there a way to do it in javascript. please help.

CodePudding user response:

You can first convert your arrayElement to a Map so that you can easily find the class values from your strings a, b, ab, etc. Then you can use .replace() with the regular expression \w to match word elements (ie: the non-operators) in your string. You can then use a function as the second argument of .replace() to grab the matched letters, and use the Map we made to grab its associated class:

const str = 'a*b-ab';
const arrayElement = [['a', 'class 1'], ['b', 'class 12'],['ab', 'class 15'],['ac', 'class 2']];

const lookup = new Map(arrayElement);
const res = str.replace(/\w /g, m => ` ${lookup.get(m)} `).trim();
console.log(res);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

If you need better browser support, this can be rewritten in ES5 like so, which is supported by many browsers, including IE11:

Show code snippet

var str = 'a*b-ab';
var arrayElement = [['a', 'class 1'], ['b', 'class 12'],['ab', 'class 15'],['ac', 'class 2']];

var lookup = arrayElement.reduce(function(acc, arr) {
  acc[arr[0]] = arr[1];
  return acc;
}, {});

var res = str.replace(/\w /g, function(m) {
  return " "   lookup[m]   " ";
}).trim();
console.log(res);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related