Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/461.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
操纵JavaScript';s括号中的子字符串匹配_Javascript_Regex - Fatal编程技术网

操纵JavaScript';s括号中的子字符串匹配

操纵JavaScript';s括号中的子字符串匹配,javascript,regex,Javascript,Regex,从 re=/(\w+)\s(\w+/; str=“约翰·史密斯”; newstr=str.replace(re,“$2,$1”); 文件编写(newstr); 是否可以以任何方式直接进一步操纵子字符串匹配?例如,有没有办法在一行中大写Smith一词?我是否可以将$2中的值传递给一个函数,该函数将大写并返回一个值,然后在这里直接使用它 如果在一行中不可能,有没有一个简单的方法可以把“约翰·史密斯”变成“史密斯,约翰” 试图弄明白这一点,但没有找到正确的语法。不,使用JavaScript的Reg


re=/(\w+)\s(\w+/;
str=“约翰·史密斯”;
newstr=str.replace(re,“$2,$1”);
文件编写(newstr);
是否可以以任何方式直接进一步操纵子字符串匹配?例如,有没有办法在一行中大写Smith一词?我是否可以将$2中的值传递给一个函数,该函数将大写并返回一个值,然后在这里直接使用它

如果在一行中不可能,有没有一个简单的方法可以把“约翰·史密斯”变成“史密斯,约翰”

试图弄明白这一点,但没有找到正确的语法。

不,使用JavaScript的RegExp对象是不可能的(一行代码)。 尝试:

输出:

SMITH, John

您应该能够执行以下操作:

newstr = str.replace(re, function(input, match1, match2) {
    return match2.toUpperCase() + ', ' + match1;
})

您只需提取匹配的子字符串并自己操作即可:

str = "John Smith";
re = /(\w+)\s(\w+)/;
results = str.match(re);
newstr = results[2].toUpperCase() + ", " + results[1];

不确定这是安全还是实现问题,但子字符串匹配不会被篡改,即使是通过其他方法连接和处理。这:
newstr=str.replace(re,('$2'+'forgreatjustice').toUpperCase()+',$1')返回John SmithFORGREATJUSTICE
newstr = str.replace(re, function(input, match1, match2) {
    return match2.toUpperCase() + ', ' + match1;
})
str = "John Smith";
re = /(\w+)\s(\w+)/;
results = str.match(re);
newstr = results[2].toUpperCase() + ", " + results[1];