I have an HTML page in which I am doing search using a javascript while returning the search text it also returns the neighbouring text, but this neighbouring text are taken as characters and not words I want a specific amount of words before and after the searched text. Can anyone help me out.
String a = "12345678A98765432";
System.out.println("My char or string is at postion " +a.indexOf('A'));
System.out.println("First 8 are "+ a.substring(a.indexOf('A')-8, a.indexOf('A')));
System.out.println("Next 8 are " +a.substring(a.indexOf('A')+1, a.indexOf('A')+9));
Result is :
My char or string is at postion 8
First 8 are 12345678
Next 8 are 98765432
You can do the same thing in java script function as well
Using regex, 8 words before and after the word eiusmod
, if you want 8 or less, you can change {8}
to {,8}
var txt = "Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua";
var result = txt.match(/((?:\s?(?:[\w]+)\s?){8})eiusmod((?:\s?(?:[\w]+)\s?){8})/);
var previousWords = result[1].trim().split(/\s/);
var nextWords = result[2].trim().split(/\s/);
Result:
> previousWords
> ["dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do"]
> nextWords
> ["tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua"]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.