dmx
dmx

Reputation: 1990

JavaScript - Search pattern in string

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.

Upvotes: 0

Views: 331

Answers (2)

hjpotter92
hjpotter92

Reputation: 80639

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

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074148

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"));
}

Upvotes: 2

Related Questions