Regex test failed in Javascript when defining expression as a class property

Osman Cea

I found this really strange behavior when defining a regex as a class property in ES6. I currently encountered this behavior working with typescript and angular, but I made a stripped version in my chrome console and it was the same.

class RegexTest {
  constructor() {
    this.expression = /[\*|\-|\_]/g;
  }

  testStringExpression(word) {
    return this.expression.test(word);
  }
}

const tester = new RegexTest();
const words = "*, *, *, kitten";

const reduced = words.split(',').reduce((acc, item, index) => {
  if ( tester.testStringExpression(item) ) {
    return acc;
  } else {
    return acc + item + index;
  }
}, "");

console.log(reduced); // Should be " kitten3", instead I'm getting " *2 kitten3"

However, If I just test the regular expression as it is inside the reduce, the result is the expected:

const words = "*, *, *, kitten";
const reduced = words.split(',').reduce((acc, item, index) => {
  if ( /[\*|\-|\_]/g.test(item) ) {
    return acc;
  } else {
    return acc + item + index;
  }
}, "");

console.log(reduced); // " kitten3"

What am I'm getting wrong here?

Shilly

From the MDN reference:

If the regex has the global flag set, test() will advance the lastIndex of the regex. A subsequent use of test() will start the search at the substring of str specified by lastIndex (exec() will also advance the lastIndex property).

So repeatedly using .test() on the same regex object, will NOT start matching the regex from the start of the string you try to match. So the first time you try to match the string "*", it will return true, since it starts searching from the start of that string.

Since the expression is a property of the class, you reuse the same regex again, the second time starting from the end of the string you send it, instead of from the start. So by the time you try to match " *", you''l get false instead of true.

By putting the regular expression inline, you create a new regex object every time, and hence the lastIndex won't get updated.

The solution here is to use the match method of words to test the regex, instead of using the regex to test the word.

So if you replace

return this.expression.test(word);

by

return word.match( this.expression );

everything will work as you expect and you get the string " kitten3".

Edit: Or you could just rewrite the regex to not use the global flag at all.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Defining a Property in a IValueConverter class

defining Partial class constructor parameters when property is an array

Error when defining inner classes in a Test class in JUnit

Error for defining class method as expression

Trouble defining a proper RegEx in Javascript

Javascript match and test returning null to DOI Regex expression

Defining tomcat property in a test running with @SpringBootTest

Defining Protege class with expression of numerical data

NameError when defining a class variable

Python NameError when defining class

Scala error when defining class

When defining an abstract class, can you force a child to define a property/method defined in a parent interface?

How do I incorporate the index of an array while defining a property of said array within a class in JavaScript?

Defining a javascript class Method as a constant

Defining custom function/property inside anonymous class

Why are parenthesis optional when defining a class, but mandatory when defining a function?

Referencing own property when defining generic type

Defining Javascript's object property by invoking function

Defining a property of a JavaScript object in terms of another

Regex test is getting failed in nodejs?

JavaScript Interview Test Failed

Javascript regex expression for underscore

Javascript - issues with regex expression

regex expression needed javascript

Stuck with regex expression in Javascript

regex expression in javascript

javascript regex (regular expression)

IE11 gives SCRIPT1002 error when defining class in javascript

Type variable is not in scope when defining type class

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive