简体   繁体   中英

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?

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"

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]); 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM