Meules Meules - 1 year ago 72
Javascript Question

Strip and replace variable if it contains two words

I was wondering how to split/replace a variable into two seperate words when the variable contains a -slash- or a comma. I want to use this so that I can create two classes on a list element and then add a gradient to that div.

I've created a script that grabs some values from a JSON file. These values can be:

  • Black

  • White

  • Black / White

How do I test if the variable contains two words or a
and then change
Black / White
to "black" and "white"? Or in the code:

<li class="black white"></li>

Below the complete script that I tried. The error I get right now is that when color is just one word (so black or white) the script breaks because
is not recognized.

$.each(custom.values, function(index, value){
var color = (value.title).toLowerCase();

colorClean = color.split('/');
one = colorClean[0].replace(/^\s*/, "").replace(/\s*$/, "");
two = colorClean[1].replace(/^\s*/, "").replace(/\s*$/, "");

// I need two variables if the string contains two words so I can do this, where var 1 and 2 are two colors:
colorClean.css("background-image", "-webkit-linear-gradient(top, var1 0%,var2 100%)");
var productHtml = '' +
'<li class="'+ colorClean +'"></li>';

productsHtml = productsHtml.join('');

$('.product.'+id+' .colours').html('<ul>'+productsHtml+'</ul>');

Answer Source

Just replace the "/"


colorClean = color.split('/');
one = colorClean[0].replace(/^\s*/, "").replace(/\s*$/, "");
two = colorClean[1].replace(/^\s*/, "").replace(/\s*$/, "");


var colorClean = color.replace("/"," ");


var colorClean = color.replace(/\s?\/\s?/," ");  //results in "black" or "white", or "black white"

There is no need to split and strip.

And since you added another requirement, you can make the array either with a different match or a split.

var colorClean = color.replace(/\s?\/\s?/," ");
var colors = colorClean.split(/\s+/);
if (colors.length===1) {
    colors[1] = colors[0];
console.log(colorClean, colors[0]. colors[1]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download