문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top