patternjavascriptModerate
replace() for translating color names
Viewed 0 times
translatingcolorreplacenamesfor
Problem
I have some code to translate some color names, and this is what I did, quick and dirty.
But I'm guessing there might be some function to replace arrays with arrays maybe, like in PHP, where you can have
But I'm guessing there might be some function to replace arrays with arrays maybe, like in PHP, where you can have
str_replace($array_of_colors, $replace_array_of_colors, $colors);.var color = colors[c].replace(/sort/i, "Black");
color = color.replace(/brun/i, "Brown");
color = color.replace(/hvit/i, "White");
color = color.replace(/oransje/i, "Orange");
color = color.replace(/gul/i, "Yellow");
color = color.replace(/beige/i, "Beige");
color = color.replace(/Mørk/i, "Dark");
color = color.replace(/Rosa/i, "Pink");
color = color.replace(/rød/i, "Red");
color = color.replace(/Blå/i, "Blue");
color = color.replace(/grå/i, "Gray");
color = color.replace(/Lys/i, "Light");
color = color.replace(/lilla/i, "Purple");Solution
You're mixing up data and logic. Separate your replaces into an associative array and iterate over that instead: (My JS is extremely bad, so this will be more pseudocode-ish)
Additionally I suggest you (just like me here) use the Array.prototype.forEach() when iterating over your
var associations;
associations['/brun/i'] = "Brown";
associations['/sort/i'] = "Black";
//add all the other associations and then
associations.forEach(runReplace);
function runReplace(value, regex, array) {
color.replace(regex, value);
}Additionally I suggest you (just like me here) use the Array.prototype.forEach() when iterating over your
colorsCode Snippets
var associations;
associations['/brun/i'] = "Brown";
associations['/sort/i'] = "Black";
//add all the other associations and then
associations.forEach(runReplace);
function runReplace(value, regex, array) {
color.replace(regex, value);
}Context
StackExchange Code Review Q#70073, answer score: 10
Revisions (0)
No revisions yet.