如何使用javascript替换字符串中最后一次出现的字符 [英] How to replace last occurrence of characters in a string using javascript
问题描述
我在找出如何用 ' 和 ' 替换字符串中最后一个 ', ' 时遇到问题:
I'm having a problem finding out how to replace the last ', ' in a string with ' and ':
有这个字符串:测试1、测试2、测试3
Having this string: test1, test2, test3
我想以:测试1、测试2和测试3
and I want to end out with: test1, test2 and test3
我正在尝试这样的事情:
I'm trying something like this:
var dialog = 'test1, test2, test3';
dialog = dialog.replace(new RegExp(', /g').lastIndex, ' and ');
但它不起作用
推荐答案
foo.replace(/,([^,]*)$/, ' and $1')
使用$
(行尾)锚点给你你的位置,并在逗号索引的右边寻找一个不包含任何进一步的模式逗号.
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.
以上完全适用于定义的要求(尽管替换字符串随意松散)但基于评论的批评,以下更好地反映了原始要求的精神.
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 $1')
)
这篇关于如何使用javascript替换字符串中最后一次出现的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!