0
Q:

javascript match

<script> 
  
    // initializing function to demonstrate match() 
    // method with "i" para 
    function matchString() { 
        var string = "Welcome to GEEKS for geeks!"; 
        var result = string.match(/eek/i); 
        document.write("Output : " + result); 
    } matchString(); 
      
</script>                     
7
//Declare Reg using slash
let reg = /abc/
//Declare using class, useful for buil a RegExp from a variable
reg = new RegExp('abc')

//Option you must know: i -> Not case sensitive, g -> match all the string
let str = 'Abc abc abc'
str.match(/abc/) //Array(1) ["abc"] match only the first and return
str.match(/abc/g) //Array(2) ["abc","abc"] match all
str.match(/abc/i) //Array(1) ["Abc"] not case sensitive
str.match(/abc/ig) //Array(3) ["Abc","abc","abc"]
//the equivalent with new RegExp is
str.match('abc', 'ig') //Array(3) ["Abc","abc","abc"]
5
// The match() method searches a string for a match against a regular expression,
// and returns the matches, as an Array object.
// If the regular expression does not include the g modifier (to perform a global search),
// the match() method will return only the first match in the string.
// This method returns null if no match is found.

let str = "The rain in SPAIN stays mainly in the plain"; 
let res1 = str.match(/ain/g); /* ["ain", "ain", "ain"] */
let res2 = str.match(/ain/); /* ["ain", index: 5, input: "The rain in SPAIN stays mainly in the plain", groups: undefined] */
let res3 = str.match(/blah/); /* null */
 
4
const match = 'some/path/123'.match(/\/(\d+)/)
const id = match[1] // '123'
2
const str = 'For more information, see Chapter 3.4.5.1';
const re = /see (chapter \d+(\.\d)*)/i;
const found = str.match(re);

console.log(found);

// logs [ 'see Chapter 3.4.5.1',
//        'Chapter 3.4.5.1',
//        '.1',
//        index: 22,
//        input: 'For more information, see Chapter 3.4.5.1' ]

// 'see Chapter 3.4.5.1' is the whole match.
// 'Chapter 3.4.5.1' was captured by '(chapter \d+(\.\d)*)'.
// '.1' was the last value captured by '(\.\d)'.
// The 'index' property (22) is the zero-based index of the whole match.
// The 'input' property is the original string that was parsed.
0
cadena = "Para más información, vea Capítulo 3.4.5.1";
expresion = /ver/i;
incluye = cadena.match(expresion);
console.log(incluye);
-1

New to Communities?

Join the community