0

Lets say I have the input value:

var input_value = "** foo ** bar **";

Then I run this:

input_value = input_value.replace(/(\*\*)([\S\s.]+)(\*\*)/g,replacer_markup);

function replacer_markup(match, p1, p2, p3, offset, string) {
  var pre = '';
  var post = '';
  if (p1 == '**')
  {
    pre = '<b>';
    post = '</b>';
  }
  return pre+p2+post
}

It will give me:

foo ** bar

But instead I want to have:

foo bar **

I want to have the smallest possible result. How can I achieve this?

Sorry for any spelling mistakes, I'm not a native speaker. Thank you for your time.

2 Answers 2

3

+ is a greedy operator — it tells the engine to match as much as it can and still allows the remainder of the regular expression to match. Use +? for a non-greedy match meaning "one or more — preferably as few as possible". Also, you can exclude the . from the character class.

([\S\s]+?)
Sign up to request clarification or add additional context in comments.

Comments

2

Make the regex non-greedy:

/(\*\*)([\S\s.]+?)(\*\*)/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.