2015-10-30 193 views
0

我需要用and替換逗號的最後一個實例。我試過這個:如何替換字符串中字符的最後一個實例?

myString = myString.replace('/_([^,]*)$/','and$1'); 

但是字符串不受影響。

任何想法?

+6

爲什麼你使用_代替,? – ergonaut

+1

我相信第一個問題是你有用單引號包裹的正則表達式。你可以'替換(/ _([^,] *)$ /,'和$ 1')'。 '/ ... /'標記正則表達式的開始和結束。 – forgivenson

+0

[如何使用javascript替換字符串中最後一次出現的字符]可能的重複(http://stackoverflow.com/questions/3829483/how-to-replace-last-occurrence-of-characters-in-a-string -using-javascript) –

回答

3

你的_而不是,和你用引號將你的正則表達式包裹起來。我想你也將需要and前添加一個空格:

myString = myString.replace(/,([^,]*)$/,'\ and$1');


編輯:

你也可以做到這一點沒有正則表達式,如果你是這樣的傾向:

str = "Maria, David, Charles, Natalie"; 
lastComma = str.lastIndexOf(','); 
newStr = str.substring(0, lastComma) + ' and' + str.substring(lastComma + 1); 

//=> "Maria, David, Charles and Natalie" 
0

你把_而不是,在你的正則表達式中。使用這一個:

myString = myString.replace(/^(.*)(,)([^,]+)$/,'$1and$3'); 
0

您使用的_代替,

myString = myString.replace('/,([^,]*)$/','and$1'); 

DEMO: https://regex101.com/r/dK9sM0/1 
0

更換了會喜歡這個:

.replace(/,(?=[^,]*$)/,' and') 
2

您需要從正則表達式中刪除',或者您需要使用RegExp()。你也可以減少積極的lookahead正則表達式。

var myString = 'abc,df,ef,shsg,dh'; 
 
myString = myString.replace(/,(?=[^,]*$)/, ' and '); 
 
// use `,` instead of `_` --^-- here 
 

 
document.write(myString);

相關問題