RegExp Methods
- turned_in_notMethods
exec()
test()
toString()
- To run below examples, try it inside
<script>
tag, in a basic html file
exec( )
It's used to find the first match
- Also used when having more than 9 '(x)' (group patterns) are used & have to access them individually
- It also modifies the 'lastIndex' property value as match found
Syntax
RegExPattern.exec(string)
Syntax- To find the length
RegExPattern.exec(string).length
Syntax- To access via index value
RegExPattern.exec(string)[index] // index starts from 0
For example :
var str="This Is a book";
var pattern=/is/ig;
alert(pattern.exec(str));
// Output: is
Matches: This Is a book
Comment : Returns the first match ('is' in above case)
Example : having more than 9 '(x)' (group patterns) are used
var str="111213141516171819202122232425";
var pattern=/(..)(..)(..)(..)(..)(..)(..)(..)(..)(..)../;
var all=pattern.exec(str);
alert(all);
// Output: 1112131415161718192021,11,12,13,14,15,16,17,18,19,20
alert(all[0]);
// Output: 1112131415161718192021
alert(all[1]);
// Output: 11
alert(all[10]);
// Output: 20
Matches: 111213141516171819202122232425
Comment : Returns the first match & all the '(x)' patterns value, you can access them individually via their index
test( )
It's used to check for a match available in a string or not & returns true or false
- It also modifies the 'lastIndex' property value as match found
Syntax
RegExPattern.test(string)
For example :
var str="This Is a book";
var pattern=/is/ig;
alert(pattern.test(str));
// Output: true
Comment : Check, match found or not ('true' in above case)
toString( )
It's used to get the string value of the regular expression
Syntax
RegExPattern.toString()
For example :
var str="This Is a book";
var pattern=/is/ig;
alert(pattern.toString());
// Output: /is/ig
Comment : Returns the string value of the pattern ('/is/ig' in above case)