如何使用javascript替换字符串中最后一次出现的字符

IT技术 javascript regex replace
2021-01-23 10:00:29

我在找出如何用 ' 和 ' 替换字符串中的最后一个 ', ' 时遇到问题:

有这个字符串:test1、test2、test3

我想以:test1、test2 和 test3 结束

我正在尝试这样的事情:

var dialog = 'test1, test2, test3';    
dialog = dialog.replace(new RegExp(', /g').lastIndex, ' and ');

但它不起作用

3个回答
foo.replace(/,([^,]*)$/, ' and $1')

使用$行尾)锚点为您提供位置,并在逗号索引右侧查找不包含任何其他逗号的模式。

编辑:

以上完全适用于定义的要求(尽管替换字符串随意松散)但基于评论的批评,以下更好地反映了原始要求的精神。

console.log( 
   'test1, test2, test3'.replace(/,\s([^,]+)$/, ' and $1') 
)

我明白了Error: unexpected '/' in "foo.replace(/"
2021-03-14 10:00:29
+1,可能比使用\w飞溅更好,因为它更具包容性,例如:jsbin.com/utedu/2
2021-03-27 10:00:29
这也匹配test1, test2,test1, test2 and 为其生成它还会为原始输入字符串插入一个多余的空格字符,因为它忘记匹配,.
2021-03-27 10:00:29
@splash - 见编辑。如果要求比表达的更详细,我非常有信心 OP 可以自己进行修改,我不想对人们真正想说的话做出假设。
2021-04-08 10:00:29
我已经 根据 regex101 站点上的这个答案制作了一个示例正则表达式
2021-04-13 10:00:29
result = dialog.replace(/,\s(\w+)$/, " and $1");

$1(\w+)的是比赛的第一个捕获组

对于像“test-1、test-2、test-3”这样的字符串,这将失败,但我再次相信 OP 可以自己进行此类调整。
2021-03-26 10:00:29

正则表达式搜索模式 \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
只缺少一个空格