Reputation: 21
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 :)
Upvotes: 1
Views: 85
Reputation: 15268
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 i
th 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"))
Upvotes: 1