Skip to content

Latest commit

 

History

History
34 lines (27 loc) · 909 Bytes

regex-second-test-fail.md

File metadata and controls

34 lines (27 loc) · 909 Bytes

Question

With regular expression, pay attention to lastIndex property when g option is set,

// When set with `g` option, we have the problem.
var $zhReg = new RegExp('[\u4E00-\u9FA5\uF900-\uFA2D]', 'g');
$zhReg.test('test中'); // true
$zhReg.test('test中'); // false
$zhReg.test('test中'); // true
$zhReg.test('test中'); // false

Solution

// reset lastIndex property
var zhReg1 = new RegExp('[\u4E00-\u9FA5\uF900-\uFA2D]', 'g');
zhReg1.test('test中'); // true
zhReg1.lastIndex = 0;
zhReg1.test('test中'); // true
zhReg1.lastIndex = 0;
zhReg1.test('test中'); // true

// only use `g` when necessary
var zhReg2 = new RegExp('[\u4E00-\u9FA5\uF900-\uFA2D]');
zhReg2.test('test中'); // true
zhReg2.test('test中'); // true

References