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:
/:(w+s*)+/gSeparates the:nokibul amin mezba jomadderas a group.- Replace the group with index-wise templating
{0},{1}…{n}. - Mapping the groups. Ex:
:nokibul amin mezba jomadderto:nokibul_amin_mezba_jomadder. - 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);