Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
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

class 1 * class 12 - class 15

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!