简体   繁体   English

如何在JavaScript中用正则表达式引用所有变量名

[英]How to quote all variable names with a regex in javascript

I have a string like this: 我有一个像这样的字符串:

"xyz([x,3],x,[x,y],{y:1})" needs to be "xyz(['x',3],'x',['x','y'],{'y':1})"

Note : Variables can be in this case any letter from a to z 注意 :在这种情况下,变量可以是从az任何字母

I need to replace variables like x, y and z with their quoted versions 我需要将x,y和z等变量替换为其引用的版本

In my test the comma is being captured by the regex, the problem is that if I capture x then y is not captured because of the intersecting comma. 在我的测试中,正则表达式捕获了逗号,问题是如果我捕获x,则由于相交的逗号而不会捕获y。

var str = "xyz([x,3],x,[x,y],{y:1})"
str.replace(/(\W)([a-z])(\W)/g,"$1'$2'$3")
//output: mul(['x',3],'x',['x',y],{'y':1})

Added example: JSFiddle 添加的示例: JSFiddle

Is there a way to specify the surrounding elements without capturing them? 有没有一种方法可以指定周围的元素而不捕获它们?

This will replace the variable before comma or colon. 这将替换逗号或冒号之前的变量。

    var txt="xyz([x,3],x,[x,y],{y:1})";

    txt.replace(/[a-z]+[,:\])]/g, function f(x){
       return "'"+x.replace(/[,:\]\)]/g,"")+"'"+x[x.length-1];
   })

You are adding capture groups with that are creating issues. 您正在添加捕获组,从而造成问题。 Remove them and use: 删除它们并使用:

\W([a-z])\W

Here is a working version. 是一个工作版本。

Update 更新资料

Working with your js, 使用您的js,

var original = "xyz([x,3],x,[x,y],{y:1})"
var replaced = original.replace(/([a-z])/g, "'$1'")

and I've updated the fiddle. 我已经更新了小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM