博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Replace涵數

Posted on 2010-12-07 23:52  ☆Keep★Moving☆  阅读(146)  评论(0编辑  收藏  举报

sContent為字符串,sPattern為要替換的單引號,sReplexp為替換成雙引號

function ReplaceString(sContent, sPattern, sReplexp)

{

        var arrSingle;

        var   sReturnString;

       

//      split 的工作原理:"as'asdf'asd'''f".split(sPattern)

//      轉換後會變為[as], [asdf], [asd], [], [], [f]

        if(sContent.length > 0)

        {

                if(sContent.indexOf(sPattern) >=0)

                {

                        arrSingle = sContent.split(sPattern);

                        sReturnString = "";

                       

                        //      循環只取第2維到倒數第2.1維與最後1維需要特別處理.

                        for(var i = 1; i< arrSingle.length - 1; i++)

                                sReturnString += arrSingle[i] + sReplexp;      

                       

                        //      如果第1個字符是Single Quote(單撇號), 則換為Double Quote(雙撇號)

                        if (sContent.indexOf(sPattern) ==0)

                                sReturnString = sReplexp + sReturnString;

                        else

                                sReturnString = arrSingle[0] + sReplexp + sReturnString;

                               

                        // 如果最後1個字符是Single Quote(單撇號), 則換為Double Quote(雙撇號)

                        if (sContent.lastIndexOf(sPattern) != sContent.length - 1)

                                sReturnString = sReturnString + arrSingle[arrSingle.length - 1];

                       

                        return      sReturnString;  

                }

                else

                        return sContent;

        }

        else

                return sContent;

}