我的代码用双引号替换所有对象键,但单引号的值不会被替换
var str = "db.projects.insert({'projectid':'1001','projteamname':'DBTeam','amount':100})"
var objKeysRegex = /({|,)(?:\s*)(?:')?([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*)(?:')?(?:\s*):/g;// look for object names
str = str.replace(objKeysRegex, "$1\"$2\":");// all object names should be double quoted
console.log(str)
我无法获得以下结果
Expected ouput
db.projects.insert({"projectid":"1001","projteamname":"DBTeam","amount":100})
答案 0 :(得分:0)
我相信你在这里过分复杂,如果你想做的就是替换所有这些引用,这就足够了:
var str = "db.projects.insert({'projectid':'1001','projteamname':'DBTeam','amount':100})";
alert(str.replace(/'/g, '"'));

答案 1 :(得分:0)
您可以尝试使用以下模式:
([{:,])'(\w+)'/g;
并替换为:
$1\"$2\"
var str = "db.projects.insert({'projectid':'1001','projteamname':'DBTeam','amount':100})"
var objKeysRegex = /([{:,])'(\w+)'/g;
str = str.replace(objKeysRegex, '$1\"$2\"');
alert(str)
结果:
db.projects.insert({ “专案编号”: “1001”, “projteamname”: “DBTeam”, “量”:100})