ozen
ozen

Reputation: 47

Javascript Regex Lookbehind Alternative

I want to catch word with non-space.

var paragraphy="Apple banana kişiler ki örnek foo.";
var word="kişiler"; 
var regex = new RegExp("(?:[\\s>]|^)("+word+")(?=[.,;?!]?(?:[<\\s])|$)", "gi");
console.log(paragraphy.match);

This prints: [" kişiler"] but I want this result: ["kişiler"] I must use Positive Lookbehind but it is not supported in JavaScript. Is there an alternative solution?

Upvotes: 0

Views: 586

Answers (2)

rock321987
rock321987

Reputation: 11032

JS Demo

var paragraphy="Apple ba kişiler nana ki örnek foo.";
var word="kişiler"; 
var regex = new RegExp("(?:^|\\s)("+word+")(?=\\s|$)", "gi");
var m = regex.exec(paragraphy);
document.writeln(m[1]);

Upvotes: 1

Aaron
Aaron

Reputation: 24812

Since you can't use word boundaries with unicode characters, let's match the spaces but group the word to retrieve it :

(?:^|\s)(<your word>)(?:\s|$)

After a match, group 1 should be the expected word.

For instance :

var regex = /(?:^|\s)(kişiler)(?:\s|$)/
var paragraphy="Apple banana kişiler ki örnek foo."
paragraphy.match(regex)[1]
> "kişiler"

Upvotes: 1

Related Questions