简体   繁体   中英

Javascript Regex equivalent to PHP Regex

I am finding words to highlight words with below regex in php

/(?<!\\w)".$word."(?!\\w)/

I want exact output of this regex using in javascript using regex.

Can anyone suggest above regex's javascript regex?

I want to search for the starting index - ending index of the word matched from the implemented JS regex.

You can match words using the \\b (word boundary) token, like this .

 var text = 'I want to match .word. all words that have .word. in them.'; var word = '.word.'; var regex = new RegExp('(' + escapeRegExp(word) + ')'); console.log(text.match(regex)); function escapeRegExp(str) { return str.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, "\\\\$&"); } 

Edit: Updated due to comments.

One important note: in PHP, \\w may be Unicode aware if you use /u modifier, but since you are not using that Unicode mode, the following should work the same way.

JS regex does not support lookbehinds at all. You need to convert your lookbehind to a capturing group containing two alternatives: either the start of string or a non-word char.

So, your constructor will look like

new RegExp('(^|\\W)(' + search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + ')(?!\\w)', 'g')

Here is a regex demo:

 var search = '.search.'; var rx = new RegExp('(^|\\\\W)(' + search.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&') + ')(?!\\\\w)', 'g'); var s = ".search. .search."; while ((m=rx.exec(s))!==null) { if (m[1]) { console.log(m.index+1, rx.lastIndex); } else { console.log(m.index, rx.lastIndex); } } 
 span.highlight { color: #FF0000; } 

The (^|\\\\W) will match and capture the start of string or a non-word char into Group 1 (referenced with $1 backreference from the replacement pattern) and the search word is escaped with .replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&') (just in case there are special chars like . , ( , etc.). The search word is captured into Group 2.

The lookaheads are supported the same way as in PHP, so you may use (?!\\\\w) as in the original regex.

The m.index will fetch the match start position, thus, we need to check if Group 1 is not empty. If it is not, it match a non-word symbol, so we need t increment it before using. Else, just use plain m.index . The end position is the RegExp.lastIndex property value.

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