2

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');
4
  • Replace them with what? Have you tried anything at all? Commented May 23, 2014 at 9:58
  • You need to edit your question to make it clear exactly what is your input, your desired output and what you have tried so far. Commented May 23, 2014 at 10:07
  • I have below string pattern I have to replace last "3" which does not have prefix and suffix XX var string = 'XX0XX XX7XX XX11XX XX26XX XX30XX XX38XX XX45XX 3 10.1, Belkin Keyboard Folio'; str = string.replace(/3/, '49'); Commented May 23, 2014 at 10:09
  • There is an "edit" link under your question, you should use that. Commented May 23, 2014 at 10:11

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.