Regex: question about matching

Is there a way to check if a group of characters is bordered by certain characters, but not include them in the match, thus preserving them when you call String.replace for example? Below is the only way I know of. Is there a better way?

let str = '(word)'
let regex = /([^\w])word([^\w])/g
str = str.replace(regex, '$1new word$2') 
// str now equals '(new word)'

have you checked lookaheads and lookbehinds? (careful with lookbehinds, they are not much supported)

Ah, thank you. That’s exactly what I was looking for.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.