Search code examples
javascriptregexecmascript-6lookbehind

JS regex positive look behind * not greedy when it should?


If I look at the docs, it says * should always be greedy yet in this case it is not:

// returns 'password*****' instead of 'password: *****'
'password: "something"'.replace(/(?<=password[ :]*)[^\n,]+/i, '*****') 

Solution

  • FROM TC39 DOCS lookbehind proposal

    Patterns normally match starting from the leftmost sub-pattern and move on to the sub-pattern on the right if the left sub-pattern succeeds. When contained within a lookbehind assertion, the order of matching would be reversed. Patterns would match starting from the rightmost sub-pattern and advance to the left instead. For example, given /(?<=\$\d+\.)\d+/, the pattern would first find a number and ensure first that it is preceded by . going backward, then \d+ starting from ., and lastly $ starting from where \d+ within the assertion begins. The backtracking direction would also be reversed as a result of this.


    Since your [^\n,]+ will match all the characters except new line and , so it will capture : also and your lookbehind will not see it as it is already captured by assertions after lookbehind,

    what you can do is use + which will makes sure you match atleast one space or :

    'password: "something"'.replace(/(?<=password[ :]+)[^\n,]+/i, '*****')