Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

97
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda