Reputation: 1484
Similar to my previous question I have a string with hex colours, no spaces and named colours.
#f503e1Pink59bf22greeny-green#"f7b925"orange#fffwhite
How can I split the string on each hex colour - split the string AND keep the delimiter?
#f503e1Pink
59bf22greeny-green
#"f7b925"orange
#fffwhite
The hex colours may be preceded by a # and may be surrounded by quotes and is either three or six characters long. The named colours can be any combination of characters of undetermined length.
(#?\"?[a-fA-F0-9]{3,6}\"?)
Upvotes: 0
Views: 239
Reputation: 96
If i undersood well you nee dthe following: i supposed a color (not hexa color) contain only letters . greeny-green is not a single color, is greeny and green. if this rule is eronate, please replace the [a-z]+ from the end with [a-z-]+ or include any other character needed.
var string = '#f503e1Pink59bf22greeny-green#"f7b925"orange#fffwhite',
matches= string .match(/(#?\"?[a-f0-9]{6}\"?|#?\"?[a-f0-9]{3}\"?|[a-z]+)/gi);
console.log(matches);
Upvotes: 0
Reputation: 1484
This is what I have (and it's not pretty)
str = "#f503e1Pink59bf22greeny-green#\"f7b925\"orange#fffwhite";
reg = /(#?\"?[a-fA-F0-9]{3,6}\"?)/gim
var res = str.match(reg);
str2 = str
var results = "";
h = [];
for (var i = 0; i < res.length; i++)
{
var hex = res[i];
results += hex + "\n";
h.push(hex);
str2 = str2.replace(hex, ", ");
}
sp = str2.split(", ");
// loose the first element ","
sp.shift();
alert(sp);
for (var i = 0; i < h.length; i++)
{
results += h[i] + " " + sp[i] + "\n";
}
alert(results);
Upvotes: 0
Reputation: 92884
As other colleagues mentioned: there's no 100% working solution for your current input that will cover all possible cases.
To cover your particular input and output consider the following approach using String.match()
function:
var str = '#f503e1Pink59bf22greeny-green#"f7b925"orange#fffwhite',
colors = str.match(/#?\"?[a-f0-9]{3,6}\"?[a-z-]+/gi);
console.log(colors);
Upvotes: 1