Javascript Replace with parameters

2492 views javascript
2

So I'm making a markdown editor, and I want some function like "This is *italics*".replace("*$1*","<i>$1</i>");

Any easy way to do this? (Client Side, this'll be hosted on Github Pages or something, so a random npm package probably won't help)

answered question

Please add more examples of what you want to achieve.

Try "this is *italics*".replace(/\B(\*)(.+)(\*)\B/,"<i>$2</i>")

1 Answer

3

Short answer: 'This is *italics*'.replace(/\*(.+)\*/g, '<i>$1</i>');


Explanation: Using RegExp is the easiest way to go about this, specifically the grouping section. Let's strip down /\*(.+)\*/:

  1. The starting and ending / are defining that the thing in between is actually a RegExp
  2. We need to check for asterisks at the start and at the end, but * is a quantity selector in the RegExp, therefore we need to escape them using a \ (basically saying "hey, the next chracter is not an actual selector, but something literal")
  3. Next we need to specify that we need to check for any character between those asterisks (that's the .), appearing more than once (that's the +)
  4. Finally we need to group this and tell the RegExp that what we want to remember is the thing between the asterisks and not the whole thing, that's where the parenthesis come to action.
  5. Using those parenthesis, we can do $n (where n is the matched quantity number, in this case 1) in the replacing string to replace for the matching group

posted this

Have an answer?

JD

Please login first before posting an answer.