Open In App

JavaScript RegExp ? Quantifier

Improve
Improve
Like Article
Like
Save
Share
Report

The m? Quantifier in JavaScript is used to find the match of any string that contains zero or one occurrence of m. 

Syntax: 

/m?/ 

or

new RegExp("m?")

Syntax with modifiers:

/\m?/g 

or

new RegExp("m?", "g")

Example 1: This example matches the word e followed by zero or one occurrence of k. 

Javascript




function geek() {
    let str1 = "GeeksforGeeks@_123_$";
    let regex4 = /ek?/gi;
    let match4 = str1.match(regex4);
 
    console.log("Found " + match4.length
        + " matches: " + match4);
}
geek();


Output

Found 4 matches: e,ek,e,ek

Example 2: This example replaces the word 1 followed by zero or one occurrence of 2 with “@”. 

Javascript




function geek() {
    let str1 = "Geeky#12$#1";
    let regex4 = new RegExp("#12?", "gi");
    let replace = "@";
    let match4 = str1.replace(regex4, replace);
    console.log(" New string: " + match4);
}
geek();


Output

 New string: Geeky@$@

Supported Browsers: The browsers supported by RegExp ? Quantifier are listed below:

  • Google Chrome
  • Apple Safari
  • Mozilla Firefox
  • Opera
  • Internet Explorer

We have a complete list of Javascript RegExp expressions, to check those please go through this JavaScript RegExp Complete Reference article.


Last Updated : 29 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads