Reputation: 93
I wrote this js to pull values from select statements to build a link that the user will be sent to. The problem is that I am using this with Shopify where the products are stored under
/products/handle
and Shopify uses '-' to replace '.' in links.
I have tried many different ways of using the replace function using it for a single instance of the character, storing the new value in a differently named variable, and trying to perform the replace when building the link.
myForm.addEventListener('submit', function(e){
e.preventDefault();
var val1 = document.getElementById("shortSide").value;
var val2 = document.getElementById("longSide").value;
var val3 = document.getElementById("widthSide").value;
var hyph = '-';
if(val1 != "default" && val2 != "default" && val2 != "Long Side" && val3 != "default" && val3 != "Width")
window.location.href = "/products/" + val1.replace(/\./g,hyph) + "x" + val2.replace(/\./g,hyph) + "x" + val3;
else
alert("Fill out everything please!");
}, false)
If the variables contain
var1 = '16.88'
var2 = '25.25'
var3 = '1'
The expected output would be
/products/16-88x25-25x1
but the actual output is
/products/16.88x25.25x1
Upvotes: 3
Views: 613
Reputation: 9984
.
is a special character in regex (It will match any character except line terminators), you need to escape it with a backslash:
val1.replace(/\./g,hyph)
E.g.
var hyph = '-'
var val1 = '16.88'
var val2 = '25.25'
var val3 = '1'
console.log("/products/" + val1.replace(/\./g,hyph) + "x" + val2.replace(/\./g,hyph) + "x" + val3)
Upvotes: 6
Reputation: 6418
You can try this for solving your problem. .
means a character. For catching dot you have to do something like \.
;
var1 = '16.88'
var2 = '25.25'
var3 = '1';
let href = "/products/" + var1.replace(/\./g, '-') + 'x' + var2.replace(/\./g, '-') + 'x' + var3.replace(/\./g, '-');
console.log(href);
Upvotes: 0