Extracting Text Between Words(Pattern) using Regex in JavaScript

Below are the ways to extract text between words in javascript:

Given the String “Name: John Berkins Address: LA, USA”


	var data = "Name: John Berkins Address: LA, USA";
	
	//using String.indexOf + String.substring
	var name = data.substring(data.indexOf("Name:")+6,data.indexOf("Address"));
	var addr = data.substring(data.indexOf("Address:") + 9);
	alert(name);
	alert(addr);	

	//using Regex (with the use of Non-Capturing Group(?:)
	var rname = data.match(/(?:Name:)(.+)(?:Address:)/)[1];
	var raddr = data.match(/(?:Address:)(.*)/)[1];
	alert(rname);
	alert(raddr);
	
	//Note: the regex  code above may not work if the data contains \n (newline character)
	//      this is because of the (.+) expression cannot disregards \n chars,
	//      the workaround is to change it to anoter expression or to remove the \n char before
	//		the extraction process: h
	//Example:
	//
	//data = data.replace(/\n/g,' ');
	//var rname = data.match(/(?:Name:)(.+)(?:Address:)/)[1];
	//var raddr = data.match(/(?:Address:)(.*)/)[1];
	
Advertisements