1

I can't solve one problem.

There is a string in which in some places there are hex codes, codes can be many. I need to write a function that can return a string with changed codes. What was I trying to do:

function test(i,color){
 let str = "Lorem ipsum #1385ff dolor sit amet, #1385ff consectetur adipisicing #1385ff  elit. #333 Neque , est, voluptatum,#333";
 str = str.replace(str.match(/#[0-9a-f]{6}|#[0-9a-f]{3}/gi)[i],color) 
 return str
}
console.log(test(2,"#000"))

What I expected to get:

Lorem ipsum #1385ff dolor sit amet, #1385ff consectetur adipisicing #000 elit. #1385ff Neque quibusdam, est, voluptatum,#333333 aperia

What I got:

Lorem ipsum #000 dolor sit amet, #1385ff consectetur adipisicing #1385ff elit. #1385ff Neque , est, voluptatum,#333333

I will be very grateful for your help :)

Ivan V.
  • 7,593
  • 2
  • 36
  • 53
Vlad Lebed
  • 21
  • 5
  • 1
    And what are the rules for the replacement(s) ? – Jan May 12 '20 at 13:30
  • Hex codes in a string are arranged in a certain sequence, but they can have completely different values or be the same. The function must be able to change hex code with a specific index, which is passed through parameters. – Vlad Lebed May 12 '20 at 13:36
  • Have you tried [this](https://stackoverflow.com/questions/23555593/regular-expression-capture-nth-match)? – Asocia May 12 '20 at 13:43

1 Answers1

1

You can use a replacer function to count up the position you want to replace.

function test(i,color){
 let str = "Lorem ipsum #1385ff dolor sit amet, #1385ff consectetur adipisicing #1385ff  elit. #333 Neque , est, voluptatum,#333";
  var j = 0;
 str = str.replace(/#[0-9a-f]{6}|#[0-9a-f]{3}/gi,function(x){return j++!==i? x : color}) 
 return str
}
console.log(test(2,"#000"))

Another version without using replacer function. Builds a new RegExp each time that matches pattern i times, captures all that text, reinserts that text, and replaces the ith match with color

function test(i,color){
 let str = "Lorem ipsum #1385ff dolor sit amet, #1385ff consectetur adipisicing #1385ff  elit. #333 Neque , est, voluptatum,#333";
 str = str.replace(new RegExp(`((?:.*?#[0-9a-f]{6}|#[0-9a-f]{3}){${i}}.*?)(?:#[0-9a-f]{6}|#[0-9a-f]{3})`,'i'),`$1${color}`) 
 return str
}
console.log(test(2,"#000"))
user120242
  • 14,918
  • 3
  • 38
  • 52