2

Let's consider a constant main which is defined something as :

const main = "Work on $ @ & but not 1 2 3";

Now, a function named as parse() which is used as :

const final = parse(main);
alert(final); // Work on <b>$</b> <b>@</b> <b>&</b> but not 1 2 3

So, we find that the special characters i.e $, @ and &, have been updated with some html. So, firstly I tried to make the parse function, which seemed like this :

const parse = (val) => {
  val = val.replace(/\$/gim, "<b>$</b>").replace(/@/gim, "<b>@</b>").replace(/\&/gim, "<b>&</b>");
  return val;
}:

My code works but lastly I realised that I have to write a lot of code if I have to give support for all characters ! So, is there any shorcut ?

0

1 Answer 1

0

Use | which means "or" and use $& which means the matched string.

const main = "Work on $ @ & but not 1 2 3";

const parse = (val) => {
    val = val.replace(/\$|@|&/gim, "<b>"+"$&"+"</b>");
      return val;
    };

    const final = parse(main);
    alert(final); // Work on <b>$</b> <b>@</b> <b>&</b> but not 1 2 3

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

1 Comment

This is an often asked duplicate. It doesn't need an answer, just a close vote (when you can) and if necessary a comment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.