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

2
  • Possible duplicate of How to replace all occurrences of a string in JavaScript Commented Jan 27, 2019 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? Commented Jan 27, 2019 at 15:33

2 Answers 2

1

here is function for having this functionality

function changeValue(str,value){
    return str.replace(/\/qty\/[0-9]+\//,`\/qty\/${value}\/`)
}
console.log(url,4);
Sign up to request clarification or add additional context in comments.

2 Comments

ispeakphone.com/checkout/cart/add/uenc/… this one not working adding as new qty not replacing
check it again please
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.