0

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

OBAID
  • 1,299
  • 2
  • 21
  • 43
  • Possible duplicate of [How to replace all occurrences of a string in JavaScript](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – Web Nexus Jan 27 '19 at 15:25
  • Why not rather start with the string *parts* `"http://ispeakphone.com/checkout/cart/add/uenc/aHR0cDovL2lzcGVha3Bob25lLmNvbS9zYW1zdW5nL3NhbXN1bmctZ2FsYXh5LXMvZ2FsYXh5LXM5LXBsdXMuaHRtbA,,/product/619/form_key/foxmD7jgFv31xmEs/qty/";` and `"/?options=cart"`, then *build* the new string with the current value every time you need it? – Bergi Jan 27 '19 at 15:33

2 Answers2

1

here is function for having this functionality

function changeValue(str,value){
    return str.replace(/\/qty\/[0-9]+\//,`\/qty\/${value}\/`)
}
console.log(url,4);
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • http://ispeakphone.com/checkout/cart/add/uenc/aHR0cDovL2lzcGVha3Bob25lLmNvbS9zYW1zdW5nL3NhbXN1bmctZ2FsYXh5LXMvZ2FsYXh5LXM5LXBsdXMuaHRtbA,,/product/619/form_key/foxmD7jgFv31xmEsqty/2qty/4qty/6/?options=cart this one not working adding as new qty not replacing – OBAID Jan 27 '19 at 15:42
  • check it again please – Maheer Ali Jan 27 '19 at 15:46
0

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)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60