0

hello I would like to know what is the best way to search pattern like AB where A should be any except A and B should only be B ? Exempple : 'ADSDFSDAB' should return false where as 'BBBSDSSDSDNSSS' should return true.

So, for every B in my string, I want to return true if there is no A preceding it.

0

2 Answers 2

2

where A should be any except A...

So that's [^A]

and B should only be B

And that's B.

So:

if (/[^A]B/.test(str))) {
    // Yes, it has a match
} else {
    // No, it doesn't
}

Live Example:

test("ADSDFSDAB", false);
test("BBBSDSSDSDNSSS", true);

function test(str, expect) {
  var result = /[^A]B/.test(str);
  var good = !result == !expect;
  console.log("'" + str + "': " + result + (good ? " - Pass" : " - FAIL"));
}

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

Comments

1

From what I understand, you want to match B not followed by A. You can use a patter like:

[^A]B

however, I'd suggest that you search for the existence of the substring AB in your original string and check the result.

originalString.indexOf('AB') !== -1

1 Comment

[^A]B doesn't match a B at the start of the string. Searching AB with indexOf is indeed the best way.

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.