javascript - 如何使用正则表达式在javascript中查找和替换所有带有开括号且没有冒号的属性
问题描述
我在javascript中有这个字符串
id: \"test\"\nlang: \"en\"\nresult1 {\n source: \"agent\"\n},result2 : {\n source: \"agent\"\n}
我想找到所有正在进行的单词(属性),{
并且在两者之间没有:
,并用正则表达式替换它: {
,例如在上面的字符串中有result1
and result2
,所以我只想result1
成为result1 :
,最终的脚本会像
id: \"test\"\nlang: \"en\"\nresult1 : {\n source: \"agent\"\n},result2 : {\n source: \"agent\"\n}
解决方案
你可以试试这样的
(\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)
推荐阅读
- rstudio - “权限被拒绝”将 .zip 下载到 RStudio
- maven - Move and IntelliJ/Maven project to another PC with IntelliJ but no internet access
- angular - 无法为 Angular 中的组件匹配任何路由器
- go - Golang 和 gcloud API:如何获取身份验证令牌
- swagger - swagger-codegen 如何自动生成应用和dockerfile?
- reactjs - 反应,事件功能很少
- vue.js - 如何将 URL 引用到 Vue.Component.Template
- node.js - 如何从 nodejs http 请求中取回数据?
- java - 从外部配置文件读取值返回空值
- c# - 我可以从 Web 浏览器控制统一的独立应用程序吗?