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
2
Answers
.
is a special character in regex (It will match any character except line terminators), you need to escape it with a backslash:E.g.
You can try this for solving your problem.
.
means a character. For catching dot you have to do something like.
;