简体   繁体   中英

Determine if a string index is part of a Regex match in JavaScript

If I have a regular expression such as \\$.*?\\$ to select all text between pairs of $ s, how would I tell if a string index matches is in one of these matches?

I could write my own function to do this, but this feels like something that would be built-in.

For example:

let regex = /\$.*?\$/gm;
let myString = 'The $quick$ brown fox $jumps$ over the lazy $dog$';

myString[0] // false
myString[7] // true (middle of 'quick')
myString[15] // false (around 'brown' and 'fox)
myString[myString.length - 1] // true

I'm still a noob in regex, so any help is much appreciated.

 function in_match( pos, str, regex ) { let match; while ( ( match = regex.exec( str ) ) !== null) { // regex.lastIndex is the position after the last match. // And match[0] is the whole last match. if ( pos >= regex.lastIndex - match[0].length && pos < regex.lastIndex ) { // if pos is between the beginning and the end of the last match, // it is within a match, therefore, return true. return true; } } // pos is not within any match, so, return false. return false; } let regex = /\\$.*?\\$/gm; let myString = 'The $quick$ brown fox $jumps$ over the lazy $dog$'; console.log( in_match( 0, myString, regex ) ); // false console.log( in_match( 7, myString, regex ) ); // true (middle of 'quick') console.log( in_match( 15, myString, regex ) ); // false (around 'brown' and 'fox) console.log( in_match( myString.length - 1, myString, regex ) ); // true

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