Today i want to show how to extract string data using Regular Expression in Javascript.
A regular expression is an object that describes a pattern of characters.
Syntax for javascript :
/pattern/modifiers;
First we can create a simple function that will process the string extraction.
example of string input will be something like this
<p>This is just a simple example input string</p>
(
[message] => "Hello",
[desc] => "its a handshake hello!"
)
<p>The purpose is to extract message and desc pattern matching</p>
Simple function that will process the string extraction
function extract(stringInput) {
var regexp = /\[(message|desc)\](.*)/gm;
var arr = [];
while (result = regexp.exec(stringInput)) {
arr.push(result[0]);
}
return arr;
}
The 'extract' function will look for a pattern on anything that has opening bracket with the matching group either 'message' or 'desc'. And the pattern will include any words that are matching after the closing bracket!
'/g' is a flag modifier to let the regular expression to include matching pattern more than one match(all matches) and '/m' is a flag modifier to go through multi-lines of input string!
using result[0] to include all matching pattern not only strict to the result of group match only!
and because we are looking for all group matches, we need to iterate the result to get the next group match! else we will only get the first match result.
if we print the returned 'arr', we will get this output!
'/g' is a flag modifier to let the regular expression to include matching pattern more than one match(all matches) and '/m' is a flag modifier to go through multi-lines of input string!
using result[0] to include all matching pattern not only strict to the result of group match only!
and because we are looking for all group matches, we need to iterate the result to get the next group match! else we will only get the first match result.
if we print the returned 'arr', we will get this output!
[message] => "Hello", [desc] => "its a handshake hello!"
if you are not familiar with regular expression, i'll suggest to read this guide first!
if you have any question, feel free to comment down below~ I'll try my best to help you out!
Comments
Post a Comment