如何使用javascript替换字符串中最后出现的字符 [英] How to replace last occurrence of characters in a string using javascript
问题描述
我在查找如何用'和'替换字符串中的最后一个','时遇到问题:
有这个字符串:
test1,test2,test3
我想结束:
test1,test2和test3
<我正在尝试这样的事情:
var dialog ='test1,test2,test3';
dialog = dialog.replace(new RegExp(',/ g').lastIndex,'and');
但它不起作用
foo.replace(/,([^,] *)$ /,'和$ 1')
使用 $
(行尾)锚点为您提供位置,并查找逗号索引右侧的模式,该模式不包含任何逗号。
编辑:
上述内容完全适用于定义的要求(尽管替换字符串是任意松散的),但根据评论的批评,下面更能反映原始要求的精神。
console.log('test1,test2,test3'.replace(/,\s([^,] +)$ /,'和$ 1'))
I'm having a problem finding out how to replace the last ', ' in a string with ' and ':
Having this string: test1, test2, test3
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 ');
but it's not working
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.
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 $1')
)
这篇关于如何使用javascript替换字符串中最后出现的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!