Wednesday 8 November 2017

php matchall like function in javascript when exec Regex





Sorry if the question was
duplicated



I have a XML file, something
like







attr1.1

attr1.2

...



attr2.1

attr2.2




And
all I want to do is use Regex to get an array of item. For some reason, I don't want to
use jQuery here(I have read about jQuery.parseXML).
Can you show me how to get
all of the items, or something, function in javascript which like match_all() in
PHP.
And here is my
Regex,





/([\w\W]+?)<\/item>/


Thank
you!



Answer





As zerkms mentioned there are
already ways of parsing XML in javascript that offer a greater range of robustness and
flexibility. There is also one href="https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454">particularly
infamous answer to the question of attempting to parse supersets of regular
languages with regular expressions, in short, it's not the best way to go about
this.



However if you are interested in precisely
this use case, there is unfortunately no functionality like match_all from php or
findall in python's re. Have a look at href="https://stackoverflow.com/questions/3410464/how-to-find-all-occurrences-of-one-string-in-another-in-javascript">this
stackoverflow, particularly the code
block



var str = "I learned to play
the Ukulele in Lebanon."
var regex = /le/gi, result, indices =
[];
while ( (result = regex.exec(str)) ) {

indices.push(result.index);
}



In
the first answer for some detail on finding many occurrences of the same regex in a
similar fashion.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...