0

I have a requirement where I need to traverse through the string and get the first occurrence of a specific pattern like as follows,

i am a new **point**

On the occurrence of two consecutive character it must return true.

I must *not* be returned or*

The above pattern must return false.I tried to create regex following few links but the string.match method always returns null. My code,

var getFormat = function(event) {
  var element = document.getElementById('editor');
  var startIndex = element.selectionStart;
  var selectedText = element.value.slice(startIndex);
  var regex = new RegExp(/(\b(?:([*])(?!\2{2}))+\b)/)
  var stringMatch = selectedText.match(regex);
  console.log('stringMatch', stringMatch);

}
<html>

<body>

  <textarea onclick='getFormat(event);' rows='10' cols='10' id='editor'></textarea>
</body>

</html>

As I am new to regex I couldn't figure out where I am wrong.Could anyone help me out with this one?

0

1 Answer 1

1

On the occurrence of two consecutive character it must return true.

If I'm understanding you correctly. You just want to check if a string contains two consecutive characters, no matter which character. Then It should be enough doing:

(.)\1

Live Demo

This is of course assuming that it's literally any character. As in two consecutive whitespaces also being a valid match.

If you just need to check if there's two stars after each other. Then you don't really need regex at all.

s = "i am a new **point**";

if (s.indexOf("**") != -1)
    // it's a match

If it's because you need the beginning and end of the two stars.

begin = s.indexOf("**");
end = s.indexOf("**", begin + 1);

Which you with regex could do like this:

((.)\2)(.*?)\1

Live Demo

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

2 Comments

I have to check whether the string is bounded by ** or _ .If is bounded by these special characters alone it must return true.
Bounded? Do you mean whether there's two sets before and after something? Because if so I just added something in relation to that.

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.