首页 > 解决方案 > 如何使用正则表达式在javascript中查找和替换所有带有开括号且没有冒号的属性

问题描述

我在javascript中有这个字符串

id: \"test\"\nlang: \"en\"\nresult1 {\n source: \"agent\"\n},result2 : {\n source: \"agent\"\n}

我想找到所有正在进行的单词(属性),{并且在两者之间没有:,并用正则表达式替换它: {,例如在上面的字符串中有result1and result2,所以我只想result1成为result1 :,最终的脚本会像

id: \"test\"\nlang: \"en\"\nresult1 : {\n source: \"agent\"\n},result2 : {\n source: \"agent\"\n}

标签: javascriptregex

解决方案


你可以试试这样的

(\w+\s*){
  • (\w+\s*)- 一个或多个单词字符,后跟零个或多个空格
  • {- 火柴{

let str = `id: \"test\"\nlang: \"en\"\nresult1 {\n  source: \"agent\"\n},result2 : {\n  source: \"agent\"\n}`

let replaced = str.replace(/(\w+\s*){/g, "$1: {")

console.log(replaced)


推荐阅读