Skip to content
Advertisement

How to replace string using regex in javascript?

How to check a string and replace the space into “_” ?

let str = "hello @%123abc456:nokibul amin mezba jomadder% @%123abc456:nokibul% @%123abc456:nokibul amin mezba%"

str = str.replace(regex, 'something');

console.log(str);

// Output: str = "hello @%123abc456:nokibul_amin_mezba_jomadder% @%123abc456:nokibul% @%123abc456:nokibul_amin_mezba%"

Please help me out 🙂

Advertisement

Answer

Check this out. I think it’s gonna help
Hints:

  1. /:(w+s*)+/g Separates the :nokibul amin mezba jomadder as a group.
  2. Replace the group with index-wise templating {0}, {1}{n}.
  3. Mapping the groups. Ex: :nokibul amin mezba jomadder to :nokibul_amin_mezba_jomadder.
  4. Finally, replacing the templates {index} with groups.

let str = "hello @%123abc456:nokibul amin mezba jomadder% @%123abc456:nokibul% @%123abc456:nokibul amin mezba%";
/* Extracting Groups */
let groups = str.match(/:(w+s*)+/g);

/* Formatting Groups: Replacing Whitespaces with _ */
let userTags = groups.map((tag, index) => {
  /* Index wise string templating */
  str = str.replace(tag, `{${index}}`)
  return tag.replace(/s+/g, "_");
});

console.log(str);
console.log(userTags);

/* Replacing string templates with group values */
userTags.forEach((tag, index) => str = str.replace(`{${index}}`, tag));

console.log(str);
Advertisement