regex - Javascript: Some kind of preg_match with a callback on each match? -


i'm trying implement dynamic service in angular (though angular isn't big factor), , can't figure out how implement following hypothetical.

let's have regex pattern,

// should match phone number /^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/ 

and want method take given string, paragraph of text, find strings matching pattern, , run method on them replace phone numbers contacts belong in address book.

var string = "555-790-2342 one, 555-555-2344 another.";  

i can pattern.test see if matches, , search , replace, if, example, search , replace isn't one-to-one, process be? assume there's list of results, like:

var numbers = {     "555-790-2342" : "john smith",      "555-555-2344" : "bob smith",      "555-324-2342" : "dana smith" }; 

i want each pattern matched hit numbers object , replace matched number(key) appropriate name(value) numbers object. have absolutely no idea how might work.

a surprisingly little-known feature:

string.replace(/your regex here/g,function(match,sub1,sub2) {     // obvious reasons, use meaningful argument names!     // stuff     // optionally:     return match; }); 

at face value whole thing no-op, not return unmodified match replacement, discards resulting string anyway (because it's not assigned variable). callback can have side-effects, such populating object, etc.

of course, if want, can return other things too, such return numbers[match];


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -