简体   繁体   中英

Javascript how to replace string with RegExp

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

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

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM