正则表达式在javascript中的值和键周围添加双引号 [英] regular expression add double quotes around values and keys in javascript

查看:111
本文介绍了正则表达式在javascript中的值和键周围添加双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有效的JSON格式来请求ES. 我有一个类似

i need a valid JSON format to request ES. i have a string like

{ 
time:  { 
          from:now-60d,
          mode:quick,
          to:now } 
}

但是当我尝试使用JSON.parse时出现错误,因为我的字符串应该像

but when i try to use JSON.parse i got error because my string should be like

 { 
time:  { 
          "from":"now-60d",
          "mode":"quick",
          "to":"now" } 
}

所以我的问题是,有什么解决方案可以在字符串的键和值周围添加双引号吗?

so my question, there is any solution to add double quotes around keys and values of my string ?

感谢

推荐答案

也许您可以使用:

str.replace(/([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)/g, "\"$1\":\"$2\"");

这里是

regex演示

注意

在字符组[a-zA-Z0-9-]中,我使用alphabetical digits-,也许您需要其他字符,以便可以使用另一个字符

In the group [a-zA-Z0-9-] of characters i use alphabetical digits and a -, maybe you need other so you can use another one

这篇关于正则表达式在javascript中的值和键周围添加双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆