Search This Blog

2024/03/21

Javascript:Regular Expression related functions on string

Search:

The simplest regular expression related string method is search(), which
takes a regular expression argument and returns the index of the character at
which the first matching substring begins. If no substring matching the
pattern is found, –1 is returned.

Code:
var str = "The Powerpacked Javascript:The Javascript Regular Expression are Powerfull!"
console.log(str.search(/powerf.*/i))

output:
65

split():

The second method provided by string is also fairly simple. The split()
method splits (for lack of a better word) a string into substrings and
returns them in an array. It accepts a string or regular expression
argument containing the delimiter at which the string will be broken.

Code:
var delimitedString="9 |27 |36 |45 |54 |63 |72 |81 |90"

//use character classes while splitting
var pattern = /[ \|]+/
//var pattern = /[|]+/

//do not use character group while splitting
//var pattern = /( \|)+/

var arr = delimitedString.split(pattern)
console.log(arr)

Output:
[
'9', '27', '36',
'45', '54', '63',
'72', '81', '90'
]


Replace:

The replace() method returns the string that results when you replace text
matching the method’s first argument (a regular expression) with the text of
the second argument (a string). If the global (g) flag is not set in the
regular expression declaration, this method replaces only the first occurrence
of the pattern.

Code:
var landline = "912367233427"
var pattern=/(\d{2})(\d{4})(\d{6})/

//hypeneted
var formattedLandline = landline.replace(pattern,"$1-$2-$3")
console.log(formattedLandline)

output:
91-2367-233427


match( )

method takes a regular expression as an argument and returns an array
containing the results of the match. If the given regular expression has
the global (g) flag, the array returned contains the results of each substring
matched.if match() does not find a match, it returns null.

Code:
var delimitedString="9 |27 |36 |45 |54 |63 |72 |81 |90"

var pattern = /\d{1,}/g
var result = delimitedString.match(pattern)
console.log(result)

Output:
[
'9', '27', '36',
'45', '54', '63',
'72', '81', '90'
]
or

Code:
var delimitedString="9 |27 |36 |45 |54 |63 |72 |81 |90"
var pattern = /(\d{1,})/g
var result = delimitedString.match(pattern)
console.log(result)

Output:
[
'9', '27', '36',
'45', '54', '63',
'72', '81', '90'
]


No comments:

Post a Comment