日期:2014-05-16  浏览次数:20327 次

去除引号,哪里错了???
function   removeQuotation(str)   {

                  //这个if没有问题
if   (str.indexOf( "\ ' ")   !=   -1)
{
str   =   str.replace(/\ '/g   ,   "\\ ' ");
}


                 
if   (str.indexOf( "\ " ")   !=   -1)
{
                                    //这个if执行就出错
str   =   str.replace(/\ "/g,   "\\ " ");//need   more   research..
}


return   str;
}

因为str是作为参数传递的,我需要先处理,比如 '变成   \ '(比如u 's 'a会变成u\ 's\ 'a\ '),   "   变成   \ ".

可是上面的语句,处理单引号的那部分完全正确,而下边的一执行就出错。

------解决方案--------------------
//改成下面的形式就可以了
function removeQuotation(str) {

//这个if没有问题
if (str.indexOf( "\ ' ") != -1)
{
str = str.replace(/\ '/g , "\\ ' ");
}

if (str.indexOf( '\ " ') != -1)
{
//这个if执行就出错
str = str.replace(/\ "/g, '\\ " ');//need more research..
}




return str;
}
------解决方案--------------------
换成:
//这个if执行就出错
str = str.replace(/\ " "/g, "\\ " " ");//need more research..

试试看呢?

------解决方案--------------------
直接替换不好吗?
HTML code

<div id="aa">"4234'\fadf"\'sdf</div>
<script>
function removeQuotation(str) { 
return str.replace(/([\\"'])/g, "\\$1"); 
}
alert(removeQuotation(aa.innerHTML))
</script>

------解决方案--------------------
str = str.replace(/\"/g, "\\\"");