user1046987
user1046987

Reputation: 113

Regexp to replace string

I have below string pattern like Below.

"XX0XX XX7XX XX11XX XX26XX XX30XX XX38XX XX45XX **3** 10.1, Belkin Keyboard Folio"

I have to replace last "3" with "XX49XX" which does not have prefix and suffix with "XX"

I have done below code so far which is replacing first occurrence of 3 which is not correct

var string = 'XX0XX XX7XX XX11XX XX26XX XX30XX XX38XX XX45XX 3 10.1, Belkin Keyboard Folio';

str = string.replace(/3/, 'XX49XX');

Upvotes: 2

Views: 95

Answers (3)

anubhava
anubhava

Reputation: 784918

You can use use negative lookahead to match last 3:

string = string.replace(/3(?!.*3)/, 'XX49XX');

// XX0XX XX7XX XX11XX XX26XX XX30XX XX38XX XX45XX 49 10.1, Belkin Keyboard Folio

Upvotes: 2

Taemyr
Taemyr

Reputation: 3437

anubhave shows how to match the last occurence of the digit 3.

You can also match to the relevant part of the string.

string.replace(/\b\d+ (\d+\.\d+, Belkin Keyboard Folio)/, 'XX49XX')

This replaces the first number (one or more digits) in the substring with the form <number> <number>.<number>,Belkin Keyboard Folio

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

While JS sadly doesn't have the capacity for lookbehinds, you can use a lookahead:

string.replace(/3(?!\d*XX)/, "XX49XX");

This will ensure that the 3 that you get is not part of a XX##XX structure.

Upvotes: 0

Related Questions