0

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

0

2 Answers 2

4

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);

Sign up to request clarification or add additional context in comments.

1 Comment

This adds an anchor for orange as well
0

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)

2 Comments

@Taki only the static RegExp.$1 properties are deprecated. $1-$9 can still be used in the replace method. stackoverflow.com/a/53425276/3082296

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.