0
点赞
收藏
分享

微信扫一扫

js 如何对特殊字符进行转义


在生成 csv 文件时,遇到文件内容是下面 json 格式的,需要对特殊字符进行转义

'{"font":{"size":11,"name":"Calibri"},"url":"https://www.bejson.com/"}'

参照 lodash 的转义写法如下:

const reRegExpChar = /[\\"'()[\]{}|]/g;
const reHasRegExpChar = RegExp(reRegExpChar.source);
/**
 * Escapes the `RegExp` special characters "\", """, "'",
 * "(", ")", "[", "]", "{", "}", and "|" in `string`.
 *
 * @param {string} [string=''] The string to escape.
 * @returns {string} Returns the escaped string.
 *
 */
function escapeRegExp(string) {
  return (string && reHasRegExpChar.test(string))
    ? string.replace(reRegExpChar, '\\$&')
    : (string || '');
}

转义后为:

"\{\"font\":\{\"size\":11,\"name\":\"Calibri\"\},\"url\":\"https://www.bejson.com/\"\}"

这里用到了 replace 的 replacement 参数特殊用法 $&

replacement 可以是字符串,也可以是函数。如果它是字符串,那么每个匹配都将由字符串替换。但是 replacement 中的 $ 字符具有特定的含义。如下表所示,它说明从模式匹配得到的字符串将用于替换。

字符

替换文本

$1、$2、...、$99

与 regexp 中的第 1 到第 99 个子表达式相匹配的文本。

$&

与 regexp 相匹配的子串。

$`

位于匹配子串左侧的文本。

$'

位于匹配子串右侧的文本。

$$

直接量符号。

 

举报

相关推荐

0 条评论