簡體   English   中英

如何使用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(/,([^,]*)$/, ' 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:whatver4 Line3:23233

尚未找到Line2:sadXYZ!X
僅缺少空格

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM