Regular expression in javascript
example of the use, if you want to extract "my name" from this string '"name":"my name"'var ret = '"name":"my name"';
var rets = ret.match(/name[\\'"+]:[\\'"+]([^\0'"]+)/i)||[,];
you will get rets[0] = "name":"my name"
and you will get rets[1] = "my name"
explanation:
.match is the method of string type. this is actual structure .match(//i)
i -> indicate that we don't care the case
so if you have string = '"Name":"my name"' or '"nAme":"my name"' it will also work
now look at this regular expression
name >> begin of search
- we want to find the text that has "name" at the begin of the search
- your name : >> this will work
- your nnme : >> this will not work
[\\"'+] >> represent next characters after above word
- next character must be \ " or ', at least 1
- your name" : >> this will work
- your name: >> this will not work
- it can be more than 1
- your name"' :>> this will work
- your name\" :>> this will work
- your name": >> this will work
- your name""x >> this will not work
[\\"'+] >> represent next characters after above word
- next character must be \ " or ', at least 1
- your name":" >> this will work
- your name: " >> this will not work
- it can be more than 1
- your name"':" :>> this will work
- your name\":\" :>> this will work
([^\0'"]+) >> represent group of text that after above word
- it can be any character but not ascii 0 and not " and not '
- your name":"sss" :>> this will work
- your name":"sss :>> this will not work
- it can be more than 1
- your name":"s" :>> this will work
- your name":"sss" :>> this will work
let's look at the function method
ret.match(/name[\\'"+]:[\\'"+]([^\0'"]+)/i)
>> this will return array if match
>> and return null if not match
ret.match(/name[\\'"+]:[\\'"+]([^\0'"]+)/i) || [,]
>> always return array, if match will return matching array
>> if not match you will get empty array of 2 index
No comments:
Post a Comment