Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
Replace words found in string

Im trying to replace words in string with matched key and index position without removing the other words.

My desired output is: hey HI hey HELLO

What i've tried so far...

var data = {
  items: ["item", "HI", "item2"],
  moreitems: ["moreitem", "moreitem1", "HELLO"]
}
var str = "hey #items1 hey #moreitems2";

var newStr = '';
var match = str.match(/#(.*?)\d+/g); //get str that starts with # and ends with digits
for (var i = 0; i < match.length; i++) {
  var keys = match[i].replace(/#|\d+/g, ''), // remove hash and numbers to match the data keys
    pos = match[i].replace(/\D/g, ''); // get the digits in str 
 newStr += data[keys][pos] + ' ';
}
console.log(newStr)

thanks for your help!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

A simple solution would be to use replace() with a replacer function.

I use the regex /#(\D+)(\d+)/g. Matching #, followed by one or more non-digits (placed in capture group 1), followed by one or more digits (placed in capture group 2).

regex diagram
Regexper

All capture groups are passed as arguments of the replacer function. The full match is passed as the first argument, capture group 1 as the second, etc.

Within the replacer function you can then access the value based on the captured attribute name and index.

var data = {
  items: ["item", "HI", "item2"],
  moreitems: ["moreitem", "moreitem1", "HELLO"]
}
var str = "hey #items1 hey #moreitems2";

const result = str.replace(
  /#(\D+)(\d+)/g,
  (_match, attr, index) => data[attr][index]
);
console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

you can use

  • string.replace to replace the substr in the end of the process
  • calculate the index in string array by recovered the last character of match string with match[match.length - 1]
  • recover category of data to use by removing first and last character category = match.slice(0, -1).substring(1);

var data = {
  items: ["item", "HI", "item2"],
  moreitems: ["moreitem", "moreitem1", "HELLO"]
}

var str = "hey #items1 hey #moreitems2";

var newStr = str;
var match = str.match(/#(.*?)\d+/g);
var index, category;
console.log(match);

match.forEach(match => {
  index = match[match.length - 1];
  category = match.slice(0, -1).substring(1);
  newStr = newStr.replace(match, data[category][index]);
});

console.log(newStr)

about 4 years ago · Juan Pablo Isaza Relatório

0

const dic       = {
  xxx: 'hello',
  yyy: 'world',
  zzz: 'peace'
}
const string    = 'hey! #xxx, #yyy! #zzz on you'
const newString = string.replace(/#\w+/g, item => dic[item.substring(1)])

console.log(string)
console.log(newString)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda