Domanda

What I'm trying to do is add forward slash to the beginning and end of a string of text if the first and last character of the string is not /.

In my script I have:

if(!reFind('\/\S\/', myString){
    myString = '/' & arrayToList(listToArray(myString, '/\'), '/') & '/');
}

I want to run a ReReplace instead of listing to an array and then adding the slashes in.

È stato utile?

Soluzione

Using array to list and list to array could possibly remove inner slashes, so you don't want to do that. Instead, replace leading and trailing slashes with a regex.

<cfscript>
    string1 = "foobar";
    string2 = "/foobar/";
    string3 = "foo/bar";
    string4 = "/foo/bar/";

    function addSlashes (str) {
        return "/" & reReplace(str,"^/|/$","","all") & "/";
    }

    writeDump(addSlashes(string1));
    writeDump(addSlashes(string2));
    writeDump(addSlashes(string3));
    writeDump(addSlashes(string4));
</cfscript>

you can paste the above into http://www.trycf.com

Altri suggerimenti

You should just be able to replace ^/?(.*?)/?$ with /\1/.

See a visual explanation at http://www.regexper.com/

Note the pattern I use @ www.regexper.com is slightly different as I need to escape the / for a JS pattern; not so with CFML ones.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top