Reputation: 11
I have this string
"red col. yellow; col. black; col. green; orange; col. white; blue col. purple;"
and I need to get yellow, black,green, white,purple colors, just colors without 'col.' and ';' and change this string to this:
"red col. < a>yellow<\a> ; col. < a>black<\a> ; col. < a>green<\a>; orange; col. <a>white<\a>; blue; col. < a>purple<\a>;"
how can I make it with javascript reg exp, please help
Upvotes: 0
Views: 104
Reputation: 35261
You could use a capturing group to replace
like this: (Not sure of this is the most efficient way)
const str = "red col. yellow; col. black; col. green; orange; col. white; blue col. purple;"
const newStr = str.replace(/(?<=col.)(\s+)(\w+);/g, "$1<a>$2</a>;")
console.log(newStr)
Upvotes: 0
Reputation: 17664
use /\w+(?=;)/g
to match the words ending with ;
and String.replace() to replace the match with what you want :
const str = 'red col. yellow; col. black; col. green; orange; col. white; blue col. purple;';
const result = str.replace(/\w+(?=;)/g, match => '<a>' + match + '</a>');
console.log(result);
for specific colors :
const str = 'red col. yellow; col. black; col. green; orange; col. white; blue col. purple;';
const colors = ["yellow", "black", "green", "white", "purple"];
const exp = new RegExp(colors.join('|'), 'g');
const result = str.replace(exp, match => '<a>' + match + '</a>');
console.log(result);
Upvotes: 4