1

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 :)

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

Comments

1

Hint: You can use https://regex101.com/ to test whether a regex works, it supports substitution as well.

Regex being used: (\w+)[ ], to grep all words between space, and use $1_ to substitute the space to underscore.

const regex = /(\w+)[ ]/gm;
const str = `Input: str="nokibul" output: str="nokibul"

Input: str="nokibul amin" Output: str="nokibul_amin"

Input: str="nokibul amin mezba" Output: str="nokibul_amin_mezba"

Input: str="nokibul amin mezba jomadder" Output: str="nokibul_amin_mezba_jomadder"`;

const subst = `$1_`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

1 Comment

Can Please edit your regex pattern Little bit. Because I updated my formate. :)
1

Simple one liner

str.replace(/:[^%]*%/g, arg => arg.replace(/ /g, '_'))

Explanation:

/:[^%]*%/g Find all occurrences starting with : and ending at %

This will return patterns like this :nokibul amin mezba jomadder% :nokibul% :nokibul amin mezba%

Next is to replace all space characters with underscores using this replace(/ /g, '_')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.