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

2 thoughts on “Extracting Text Between Words(Pattern) using Regex in JavaScript

  1. I have data1 = “STEM|POS:N|ACT|PCPL|LEM:$a`fiEiyn|ROOT:$fE|MP|GEN”
    data2 = “STEM|POS:ADJ|LEM:$adiyd|ROOT:$dd|MS|ACC”

    How to extract a word between “ROOT:” and “|” ,
    so the output is “$fE” . for data1, and “$dd” for data2

    Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s