Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace a string with array values in javascript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class 1 * class 12 - class 15

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

>Solution :

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

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

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading