debarchito
debarchito

Reputation: 1335

How to replace all words match after a specific character but by ignoring underscore in javascript?

Lets say I have a string named target and an object named data which are defined as :

var data : {
 value_1: "Hi"
}

var target = "Replace $value_1"

So, to replace value_1 with the value set in data, I did:

target = target.replace(/\$(\w+)/gm, function(_, a) {
  console.log(a) // => value 
  // But I want value_1, I know "_" is not a word but how do I do it ?
  return data[a.trim()]
 })

Can you help me ?

Upvotes: 0

Views: 43

Answers (2)

xdeepakv
xdeepakv

Reputation: 8125

You can update regex to match the word with num.

var data = {
  value_1: "Hi",
  value_2: "how",
  value_3: "are",
  value_4: "you",
};

var target = "Replace $value_1 $value_2 $value_3 $value_4?";
const template = (str) => str.replace(/\$(\w+_\d+)/g, (_, m) => data[m]);
console.log(template(target));

You can use string literal for better handling and clean code.

Sample:

function template(strings, ...keys) {
  return (dict) =>
    keys
      .reduce(
        (m, key, i) => {
          m = m.concat(dict[key], strings[i + 1]);
          return m;
        },
        [strings[0]]
      )
      .join("");
}
const dict = {
  value_1: "Hi",
  value_2: "how",
  value_3: "are",
  value_4: "you",
};

let html = template`Replace ${"value_1"} ${"value_2"} ${"value_3"} ${"value_4"}?`;
console.log(html(dict));

Upvotes: 2

FlatAssembler
FlatAssembler

Reputation: 782

I think this will always work:

var data = {
 value_1: "Hi"
}

var target = "Replace $value_1";

target = target.replace(/\$((\w|\_)+)/gm, function(_, a) {
  console.log(a) // => value 
  // But I want value_1, I know "_" is not a word but how do I do it ?
  return data[a.trim()]
 });

console.log(target);

Upvotes: 1

Related Questions