Search code examples
regexstringcoldfusioncoldfusion-9

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')

Solution

  • 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?