快点。我有一个字符串:#user 9#I'm Alive!
,我想取出“user 9”。
到目前为止我在做:
if(variable.match(/\#/g)){
console.log(variable):
}
但输出仍然是整行。
最佳答案
使用.split()
,以拉出您想要的项目。
var variable = variable.split("#");
console.log(variable[1]);
.split()
将字符串转换为数组,并以第一个变量作为分隔符。
当然,如果您只想单独使用正则表达式,您可以这样做:
console.log(variable.match(/([^#]+)/g));
这将再次为您提供一个项目数组,但一个较小的数组,因为它不使用哈希之前的空值作为项目。此外,正如@Stephen P所述,您将需要使用捕获组(()
)来捕获您想要的项目。
关于Javascript正则表达式英镑符号之间的匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14329724/