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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3829483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:18:22  来源:igfitidea点击:

How to replace last occurrence of characters in a string using javascript

javascriptregexreplace

提问by Henrik Stenb?k

I'm having a problem finding out how to replace the last ', ' in a string with ' and ':

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

Having this string: test1, test2, test3

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

and I want to end out with: test1, test2 and test3

我想以:test1、test2 和 test3 结束

I'm trying something like this:

我正在尝试这样的事情:

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

but it's not working

但它不起作用

回答by annakata

foo.replace(/,([^,]*)$/, ' and ')

use the $(end of line) anchor to give you your position, and look for a pattern to the right of the comma index which does not include any further commas.

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

Edit:

编辑:

The above works exactly for the requirements defined (though the replacement string is arbitrarily loose) but based on criticism from comments the below better reflects the spirit of the original requirement.

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

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

回答by splash

result = dialog.replace(/,\s(\w+)$/, " and ");

$1is referring to the first capturing group (\w+)of the match.

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

回答by ricksalmon

regex search pattern \s([^,]+)$

正则表达式搜索模式 \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

Search with patterns finds Line1: whaterver4 Line3: 23233

使用模式搜索找到 Line1:whaterver4 Line3:23233

Yet doesnt find Line2: sadXYZ!X
Which is only missing a whitespace

然而没有找到 Line2: sadXYZ!X
只缺少一个空格