RegEx在开头和结尾将双引号转换为单引号

时间:2012-10-17 08:55:13

标签: javascript jquery regex

我有一个存储整个html内容的变量,如: -

getcontent = "<table style="height: 1000px; ; width: 500px;" border="1"> <tbody> <tr> <td>[<span>Assignment(for) name</span>]</td> <td>[<span>Total No of staff-months of the assignment</span>]</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </tbody> </table> "

现在我想用单引号转换第一个和最后一个双引号。

可以使用什么正则表达式,以便getcontent转换为: -

'<table style="height: 1000px; ; width: 500px;" border="1"> <tbody> <tr> <td>[<span>Assignment(for) name</span>]</td> <td>[<span>Total No of staff-months of the assignment</span>]</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </tbody> </table> '

1 个答案:

答案 0 :(得分:2)

使用锚点作为字符串的开头和结尾:

getcontent = getcontent.replace(/(^"|"$)/g, "'");

^代表字符串的开头,$代表结尾。

这假设您实际上有一个包含起始端"的字符串,而不是"中(语法上)包含的字符串,在这种情况下您的输入无效,由于字符串中没有转义"