简体   繁体   中英

Replace last occurrence of a word within a string

I am trying to replace last occurrence of a word within string.

This doesn't work:

var str = '@[Kenneth Auchenberg](contact:1) @[kenneth@auchenberg.dk](contact:7) Kenneth Auchenber';
v = str.replace(/Kenneth Auchenberg(?![sS]*Kenneth Auchenberg?)/ , '@[Kenneth Auchenberg](contact:1)');
alert(v);

This works fine, though:

var str = '-44-test alue-1564test alue';
str = str.replace(/test alue(?![\s\S]*test alue)/, 'aa');
alert(str);

JSFiddle

Why doesn't the first version work, and how can I fix it?

I have modified your input string and regexp code. First, modified [\\s\\S]*Kenneth Auchenberg and g was missing Kenneth Auchenberg';

var str = '@[Kenneth Auchenberg](contact:1) @[kenneth@auchenberg.dk](contact:7) Kenneth Auchenberg';
v = str.replace(/Kenneth Auchenberg(?![\s\S]*Kenneth Auchenberg?)/ , '@[Kenneth Auchenberg](contact:1)');
alert(v);

var str = '-44-test alue-1564test alue';
str = str.replace(/test alue(?![\s\S]*test alue)/, 'aa');
alert(str);

Search: Kenneth Auchenberg?(?!g?\\]|\\(contact)

Replace: @[Kenneth Auchenberg](contact:1)

See demo .

If you're sure the name you wanna match is at the end of the string, you can use:

/(Kenneth Auchenberg)\s*$/

Note: there's a typo in your code. The last Kenneth Auchenberg is written as Kenneth Auchenber (with a missing 'g' at the end).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM