Alternative javascript alternative

I tried using lookahead / lookbehind in JavaScript (described in Regular-Expressions.info ) and realized that they were not supported.

What I'm trying to do is catch dar, which should not be followed win. So, the string darblablashould return true, but it darwinblablashould be false.

Now my decision: /dar/i.test(string) && !/darwin/i.test(string).

It looks pretty long, is there a shorter solution (regex string?) That can replace the current statement?

+4
source share
3 answers

Here is the solution

^dar(?!win)

Regular expression visualization

Demo version of Debuggex

EDIT

Regarding your second question

^(?!cyg)win

Regular expression visualization

Demo version of Debuggex

+1
source

Javascript .

alert(/dar(?!win)/.test('darblahblah'))
alert(/dar(?!win)/.test('darwin'))
Hide result
+1

You cannot use look-backs in JavaScript, but you can use advances.

So this will give false:

document.write(/\bdar(?!win)/i.test("darwin"));
Run codeHide result

As for the look, in most cases you can get around this limitation by using capture groups, return lines and matches, or by creating your own parsers.

Here is a way to combine /win/i.test(string) && !/cyg win/i.test(string):

document.write(/niw(?!\s+gyc\b)/.test('cyg win'.split("").reverse().join("")));
document.write("<br/>");
document.write(/niw(?!\s+gyc\b)/.test('darwin'.split("").reverse().join("")));
Run codeHide result

Note that the - niw(?!\s+gyc\b)- pattern must be canceled.

+1
source

All Articles