Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coldfusion string replace with ReReplace

I'm trying to replace spaces in a string with underscore for slug creation using RegEx. Its works fine when there is one space. But when there is two consecutive spaces or a space followed by an underscore and vice versa(' _' OR '_ ') its replaced as __. How can i overcome this? that is I want a single underscore instead of double or triple. Any help would be appreciated.

My code for replacing is similar to this.

rereplace(lCase('this is a sample _string'),'[ ]','_','all')
like image 587
Marikkani Chelladurai Avatar asked Dec 26 '22 18:12

Marikkani Chelladurai


1 Answers

This seems to do the trick, based on your revised requirement:

original = "string with_mix _ of  spaces__and_ _underscores__  __to_ _test  with";
updated = reReplace(original, "[ _]+", "_", "all");
writeOutput(updated);

Results in:

string_with_mix_of_spaces_and_underscores_to_test_with

Is that to spec?

like image 125
Adam Cameron Avatar answered Jan 10 '23 21:01

Adam Cameron