How to check a string and replace the space into “_” ?
JavaScript
x
8
1
let str = "hello @%123abc456:nokibul amin mezba jomadder% @%123abc456:nokibul% @%123abc456:nokibul amin mezba%"
2
3
str = str.replace(regex, 'something');
4
5
console.log(str);
6
7
// Output: str = "hello @%123abc456:nokibul_amin_mezba_jomadder% @%123abc456:nokibul% @%123abc456:nokibul_amin_mezba%"
8
Please help me out 🙂
Advertisement
Answer
Check this out. I think it’s gonna help
Hints:
/:(w+s*)+/g
Separates the:nokibul amin mezba jomadder
as a group.- Replace the group with index-wise templating
{0}
,{1}
…{n}
. - Mapping the groups. Ex:
:nokibul amin mezba jomadder
to:nokibul_amin_mezba_jomadder
. - Finally, replacing the templates
{index}
with groups.
JavaScript
1
18
18
1
let str = "hello @%123abc456:nokibul amin mezba jomadder% @%123abc456:nokibul% @%123abc456:nokibul amin mezba%";
2
/* Extracting Groups */
3
let groups = str.match(/:(w+s*)+/g);
4
5
/* Formatting Groups: Replacing Whitespaces with _ */
6
let userTags = groups.map((tag, index) => {
7
/* Index wise string templating */
8
str = str.replace(tag, `{${index}}`)
9
return tag.replace(/s+/g, "_");
10
});
11
12
console.log(str);
13
console.log(userTags);
14
15
/* Replacing string templates with group values */
16
userTags.forEach((tag, index) => str = str.replace(`{${index}}`, tag));
17
18
console.log(str);