js正则多次替换有没有优雅的写法?

这段代码用来规范json字符串,有没有优雅的写法?

var gLoginQstr = '{firstname: jack, lastname: li, age: 30}';
gLoginQstr = gLoginQstr.replace("{", "{\"");
gLoginQstr = gLoginQstr.replace(/:/g, "\":\"");
gLoginQstr = gLoginQstr.replace(/,/g, "\",\"");
gLoginQstr = gLoginQstr.replace("}", "\"}");
console.log(gLoginQstr );
阅读 994
5 个回答

查表法:

/**
 * @function groupReplace
 * @param {string} str
 * @param {Map<RegExp|string, string>} map
 * */
function groupReplace(map, str){
  let result = str;
  map.forEach(function(key, val){
    result = result.replace(key, val);
  });
  return result;
}

console.log(groupReplace(
  '{firstname: jack, lastname: li, age: 30}',
  new Map([
    [/\{ */, "{\""],
    [/: */g, "\":\""],
    [/, */g, "\",\""],
    [/\} */, "\"}"]
  ])
))

分组正则匹配法:

gLoginQstr = gLoginQstr.replaceAll(/(\{ *)|(: *)|(, *)|(\} *)/g, (_, $1, $2, $3, $4) => {
  if($1 !== undefined) return "{\"";
  if($2 !== undefined) return "\":\"";
  if($3 !== undefined) return "\",\"";
  if($4 !== undefined) return "\"}";
  return ""
});

正则里面加的 *是为了去除目标值前面的空格,否则"jack"会变成" jack"
但是这样的写法显然只能处理最简单的 JSONLike 字符串,稍微复杂一点就不行了。

"{a:1,b:2}".replace(/[{}:,]/ig, str => `\\${str}`)

好像只能 \,我浏览器里面试着 \ 死活不行

来个简洁的。

  1. 定义一下映射关系;
  2. 去除空格;
const obj = {
    '{': '{"',
    ':': '":"',
    ',': '","',
    '}': '"}',
};

var gLoginQstr = '{firstname: jack, lastname: li, age: 30}';
gLoginQstr.replace(/(({|:|,|})\s*)/g, $1 => obj[$1.trim()]);

console.log(gLoginQstr); // '{"firstname":"jack","lastname":"li","age":"30"}'
var gLoginQstr = '{firstname: jack, lastname: li, age: 30}';
gLoginQstr = gLoginQstr.replace(/\b/g, "\"");
console.log(gLoginQstr );

来一个野一点的吧:

let gLoginQstr = '{firstname: jack, lastname: li, age: 30}';
gLoginQstr = gLoginQstr.replace(/[^\{\}\:\,\s]+/ig, str => `"${str}"`)
console.log(gLoginQstr );

希望能帮助到你。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏