TransWikia.com

How to use regex pattern W in javascript

Stack Overflow Asked by Jitendra Yadav on December 7, 2021

I have a regex pattern for matching special characters

ptr = /W|_/g 

It’s working fine for every special character except *

Here is the my testing results

ptr = /W|_/g
ptr.test('vbk_')
true
ptr.test('vbk*')
false
ptr.test("Select * from user")
true
ptr.test("Select * from user")
true
ptr.test("Select * from user")
true
ptr.test('vbk*')
false

When I remove global(g) from the pattern it seems working fine can anyone suggest me why this happening

Here are my testing results:

ptr = /W|_/
ptr.test('vbk*')
true
ptr.test('vbk')
false
ptr.test('Select * from user')
true

One Answer

You have to reset the lastIndex or reinitialize the regex pattern.

This happens because when using g (global), there is a value called lastIndex which refers to the last match index. When reusing the same instance of your regex, the search will continue from there.

> ptr = /W|_/g
/W|_/g
> ptr.test('vbk*')
true
> ptr.lastIndex
4
> ptr.lastIndex = 0
0
> ptr.test('vbk*')
true

The other way is to have a function that returns the regex value:

> ptr = () => /W|_/g
[Function: ptr]
> ptr().test("vbk*")
true
> ptr().test("vbk*")
true
> ptr().test("vbk*")
true
> ptr().test("vbk*")
true

The lastIndex is useful if you need to start the search from a specific index, otherwise, if you do not need that, simply do not use the global flag.

Answered by Ionică Bizău on December 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP