Reputation: 1539
I have a String having URL like:
var url ="http://ispeakphone.com/checkout/cart/add/uenc/aHR0cDovL2lzcGVha3Bob25lLmNvbS9zYW1zdW5nL3NhbXN1bmctZ2FsYXh5LXMvZ2FsYXh5LXM5LXBsdXMuaHRtbA,,/product/619/form_key/foxmD7jgFv31xmEs/qty/3/?options=cart";
I am getting quantity on button click from input as well like:
var qty = jQuery(this).siblings('.quantity-field').val(); // 4
How can I change this qty in URL String "/qty/3/"
to "/qty/4/"
on every time I get new value from input on button click?
I can't simply find and replace because i don't know /qty/3
exact number its dynamic it could be 2,3,4,5 etc
Upvotes: 0
Views: 168
Reputation: 36564
here is function for having this functionality
function changeValue(str,value){
return str.replace(/\/qty\/[0-9]+\//,`\/qty\/${value}\/`)
}
console.log(url,4);
Upvotes: 1
Reputation: 37755
You can use replace method.
capture everything up to /qty
in group 1 (g1)
, all the following digits in group 2 (g2)
, and remaining in group 3 (g3)
, in callback change value of group 2
as required.
var url ="http://ispeakphone.com/checkout/cart/add/uenc/aHR0cDovL2lzcGVha3Bob25lLmNvbS9zYW1zdW5nL3NhbXN1bmctZ2FsYXh5LXMvZ2FsYXh5LXM5LXBsdXMuaHRtbA,,/product/619/form_key/foxmD7jgFv31xmEs/qty/3/?options=cart";
let desired = url.replace(/^(.*\/qty\/)(\d+)(.*)$/g, function(match,g1,g2,g3){
return g1+ (Number(g2)+1) + g3
})
console.log(desired)
Upvotes: 0