Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing characters in a string using replace()

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
like image 299
Zach Avatar asked Feb 20 '26 14:02

Zach


1 Answers

. 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)
like image 127
DBS Avatar answered Feb 23 '26 03:02

DBS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!