I have the following string :
11110000111100000000111100001111000000
In this string, I would like to replace the 0
s that appear less than 6 times one after the other. If they appear 6 times or more, I would like to keep them.
(Replace them with a dot for instance)
The end result should then be
1111....1111000000001111....1111000000
I thought about using the negative lookahead and tried it, but I'm not sure how it works in that particular use-case.
Would someone be able to help me ?
My current, not working regex is
/(?!0{6,})0{1,5}/g
EDIT
After playing around a bit, I found this regex :
/((?:^|1)(?!0{6,})0{1,5})/g
but it captures the 1
before the 0
s. Would there be a way to exclude this 1
from getting caught in the regex ?
CodePudding user response:
Javascript replace
can take a function as replacement, e.g.:
let res = s.replace(/0 /g, m => {
return (x = m.length) < 6 ? '.'.repeat(x) : m;
});
There is not much to explain. Matching one or more 0
. If the match is below 6 characters, return a string composed of its length repeated replacement character, else return the full match.