Need help with Regular Expression to limit occurances of repeated string

We are using CK Editor to allow users to create pages for a website.

There is a scenario where there can be build up of the following

<p>&nbsp;</p>

<p>&nbsp;</p>

<p>&nbsp;</p>

I am attempting to use reReplaceNoCase to replace any occurances where this string exists more than 2 times, and replace it with

<p>&nbsp;</p><p>&nbsp;</p>

So that if the string being checked ever has 3 or more instances of <p>&nbsp;</p> it will replace them with 2. Ensuring there are always no more than 2 <p>&nbsp;</p>.

I managed to get a RE working for this in Javascript, but am trying to get the same RE working in Lucee, with no luck.

Here is what i currently have:

data.contentBody("
		<p>some text</p>
		<p>&nbsp;</p>

		<p>&nbsp;</p>
		
		<p>&nbsp;</p>
		");
		
		data.contentBody = reReplaceNoCase(data.contentBody,'/(<p>&nbsp;<\/p>\s*){2,}/g','<p>&nbsp;</p><p>&nbsp;</p>', 'ALL');

		//should result in data.contentBody container "<p>some text</p><p>&nbsp;</p><p>&nbsp;</p>"

But not working. That same RE works fine in Javascript, any suggestions on what i need to do to get this working in Lucee?

Thanks in advance for any pointers!

Jason

You’re close. \x\g is a global search in JS that will find all occurrences of x in the string. That part can be omitted here as it’s not valid in CFML.

Try:

data.contentBody = reReplaceNoCase(data.contentBody, '(<p>&nbsp;<\/p>\s*){2,}', '<p>&nbsp;</p><p>&nbsp;</p>', 'ALL');

Or you can shorten the argument containing what to replace with and do:

data.contentBody = reReplaceNoCase(data.contentBody, '(<p>&nbsp;<\/p>\s*){2,}', '\1\1', 'ALL');
1 Like

Tony, that worked a treat! Thanks for your help! Legend!

Jason