Click here to Skip to main content
14,332,142 members
Rate this:
Please Sign up or sign in to vote.
See more:
let american = "color";
let rainbowRegex= /colou?r/;
rainbowRegex.test(american); // Returns true -- why?


What I have tried:

to understand and try another examples. but still, i understand nothing
Posted
Updated 10-Mar-19 23:53pm
Rate this:
Please Sign up or sign in to vote.

Solution 1

Because '?' on it's own (without '*' or '+' in front of it) says "zero or one" of the preceding element.
So "colou?r" matches either "color" or "colour" but not "colotr".

As I suggested last time, get a copy of Expresso[^] - it's free, and it examines and generates Regular expressions.
It would have explained this to you!
   
v2
Comments
Member 14105304 11-Mar-19 5:52am
   
so the '?' just dismiss the behind word of it and then checks?
OriginalGriff 11-Mar-19 6:00am
   
No, read what I said:

'?' on it's own ... says "zero or one" of the preceding element.


Since the preceding element is a single character 'u' it says "zero or one 'u'"
To "disregard a word" you'd have to make it a group:
"(colou)?r" would match "colour" or "r" because "colou" is a group and that acts as the preceding element for the '?'

Seriously, download Expresso and try it - it will help you understand!
Rate this:
Please Sign up or sign in to vote.

Solution 2

The u is optional in the regex, as denoted by the ?

So both 'color' and 'colour' will match.

Type colou?r in to the regex box on here to see:

Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 3

Quote:
'? ' - Regular expression - js

Advice: read documentation.

Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx: Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
This site also show the Regex in a nice graph but can't test what match the RegEx: Regexper[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100