我在找出如何用 ' 和 ' 替换字符串中的最后一个 ', ' 时遇到问题:
有这个字符串:test1、test2、test3
我想以:test1、test2 和 test3 结束
我正在尝试这样的事情:
var dialog = 'test1, test2, test3';
dialog = dialog.replace(new RegExp(', /g').lastIndex, ' and ');
但它不起作用
我在找出如何用 ' 和 ' 替换字符串中的最后一个 ', ' 时遇到问题:
有这个字符串:test1、test2、test3
我想以:test1、test2 和 test3 结束
我正在尝试这样的事情:
var dialog = 'test1, test2, test3';
dialog = dialog.replace(new RegExp(', /g').lastIndex, ' and ');
但它不起作用
foo.replace(/,([^,]*)$/, ' and $1')
使用$(行尾)锚点为您提供位置,并在逗号索引右侧查找不包含任何其他逗号的模式。
编辑:
以上完全适用于定义的要求(尽管替换字符串随意松散)但基于评论的批评,以下更好地反映了原始要求的精神。
console.log(
'test1, test2, test3'.replace(/,\s([^,]+)$/, ' and $1')
)
result = dialog.replace(/,\s(\w+)$/, " and $1");
$1指(\w+)的是比赛的第一个捕获组。
正则表达式搜索模式 \s([^,]+)$
Line1: If not, sdsdsdsdsa sas ., sad, whaterver4
Line2: If not, fs sadXD sad , ,sadXYZ!X
Line3: If not d,,sds,, sasa sd a, sds, 23233
使用模式搜索找到 Line1:whaterver4 Line3:23233
然而没有找到 Line2: sadXYZ!X
只缺少一个空格