Dhruv Patel
Dhruv Patel

Reputation: 404

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) @[[email protected]](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?

Upvotes: 0

Views: 132

Answers (3)

HolografixFinn
HolografixFinn

Reputation: 238

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).

Upvotes: 0

Valijon
Valijon

Reputation: 13103

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) @[[email protected]](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);

Upvotes: 1

zx81
zx81

Reputation: 41838

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

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

See demo.

Upvotes: 0

Related Questions