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];
Jim 7:50 am on September 6, 2009 Permalink |
What if the selected text is repeated within the content?
“textArea.value.indexOf” will return the first instance of the selected text, but that may not be the text that is actually selected, they are just the same because they are repeated.
For example: “My name is Fred, and his name is John.”
If I select the second instance of “name is”, when I run your function I will get the first. This isn’t a problem if you just want to know the text that is selected, but it is if you want to manipulate it.
jmaglasang 1:59 pm on September 10, 2009 Permalink |
You have a point there them, I have update the code but there is still a little problem, it cannot return the correct caret position in IE.