javascript - Extract matched text and its neighboring context n words upstream n words downstream (nth occurrence from left and nth occurrence from right) -
i need text fits nicely in autocomplete dropdown. required more strategy appear. using hidden text or fadeout option didn't work because matched text string outside of visible frame of context. ellipsis approach bit heavier weight need. "show more" works well, not in context of dropdown box; don't want user worry except selection of option. want line or 2 of context centred around matched token. there related answers, nothing quite addresses need both n right , n left.
var haystack = "r4 r3 r2 r1 needle r1 r2 r3"; var needle = "needle"; var delim = " "; var numwords = 5; var trimmedtext = trimtoneighboringtext(haystack, needle, numwords, delim); console.log("with " + numwords + " neighboring words: \"" + trimmedtext + "\"");
regex can simplify lot!
here solution:
var haystack = "l5 l4 l3 l2 l1 needle r1 r2 r3 r4 r5 r6", needle = "needle", numwords = 3; var result = haystack.match("(?:\\s?(?:[\\w]+)\\s?){"+numwords+"}"+needle+"(?:\\s?(?:[\\w]+)\\s?){"+numwords+"}"); console.log("with " + numwords + " neighboring words: \"" + result[0] + "\""); with 3 neighboring words: " l3 l2 l1 needle r1 r2 r3 "
Comments
Post a Comment