Forum Moderators: open
var patt = /pat+ern/i;
while (patt.test(a))
a = a.replace(patt, 'replacement'); while (/(pat+ern)/i.test(a))
a = a.replace(RegExp.$1, 'replacement'); output = output.replace(/\./g,"\\.")(Example picked purely because it's the first replace in my logscripts.js file.)
function limitRepeatedChars(str) {
// Use a regular expression to match any sequence of 6 or more repeated characters
return str.replace(/(.)\1{6,}/g, (match) => {
// Replace the matched sequence with the first 6 characters
return match.substring(0, 6);
});
}
Yeah, the while loop is inefficient and shouldn't be needed, unless you're trying to prevent something like this, where the result of a replacement creates a new instance of the string you want to replace (because of the surrounding values):
// the link
a = `<a href="http://www.foo.com?utm_foo=bar&fbid=junk&id=123&parm=789">foo</a>`;
// remove utm_foo, ocid, trkid, gclid, fbid, data-bar, role, cite, itxt
//
// first version, using /g and no while()
// starts with "<a", followed by anything or nothing until it gets to "href=", followed by
// either a " or ', followed by anything that's not that matching " or ' until it gets to a ?,
// then followed by anything that's not that matching " or ' until it gets to a & (with an
// optional amp;)
var tracker_match = /(<a[^>]* href=("|')[^\2]+\?[^\2]*)(?:(?:&(?:amp;)*)?utm_\w+?|ocid|trkid|gclid|fbid|data-[\w-]+|role|cite|itxt[\w-]*)=\w+/gi;
a = a.replace(utm_match, '$1')
.replace(/(&(?:amp;)*)+/g, '&')
.replace(/\?(&(?:amp;)*)+/g, '?')
.replace(/(?:&(?:amp;)*)+("|')/g, '$1');
// result; removes fbid=junk, but not utm_foo=bar
// <a href="http://www.foo.com/?utm_foo=bar&id=123&parm=789">foo</a>
//////////
// second version, using while() and no /g
var tracker_match = /(<a[^>]* href=("|')[^\2]+\?[^\2]*)(?:(?:&(?:amp;)*)?utm_\w+?|ocid|trkid|gclid|fbid|data-[\w-]+|role|cite|itxt[\w-]*)=\w+/i;
while (tracker_match.test(a))
a = a.replace(tracker_match, '$1')
.replace(/(&(?:amp;)*)+/g, '&')
.replace(/\?(&(?:amp;)*)+/g, '?')
.replace(/(?:&(?:amp;)*)+("|')/g, '$1');
// result is as expected
// http://www.foo.com/?id=123&parm=789 a = a.replace(/(\?|&(?:amp;)*)(?:utm_\w+?|ocid|trkid|gclid|fbid|data-[\w-]+|role|cite|itxt[\w-]*)=\w+/gi, '$1')
.replace(/(&(?:amp;)*)+/g, '&')
.replace(/\?(&(?:amp;)*)+/g, '?')
.replace(/(&(?:amp;)*)+$/gm, ''); Likewise, your limit match example could be done like this:
a = a.replace(/((?:^[^<]|>)[^<>]*?)(([^<>])\3{6,})/g,
(match, $1, $2) => {
return $1 + $2.substring(0, 6)
}); while (($1 = /pat+ern/i).test(a))
a = a.replace($1, 'replacement'); let $1;
while (($1 = /pat+ern/i).test(a))
a = a.replace($1, 'replacement'); let $1 = /pat+ern/i;
while ($1.test(a))
a = a.replace($1, 'replacement');