4
function example(){
   var quantity = "http://www.example.com/index.php?brandid=b%123&quantity=20";
   quantity = quantity.replace(-what regular expression should i user-, "quantity=50");
}

i want to replace only the quantity=20 to quantity=50 in link. but i have tried some of the regular expression such as:

replace(/quantity=[^\d]/g,"quantity=50");
replace(/quantity=[^0-9]/g,"quantity=50");

so i would like to have some help from expertise in regular expression to help me =) thanks

1
  • Don't use the caret ^ in the [0-9] part. The caret there says to find anything but what follows. Instead, try this: [0-9]+, as it will match any number one or more times. Commented Jan 17, 2012 at 3:05

3 Answers 3

3
replace(/quantity=[\d]+/g,"quantity=50")
Sign up to request clarification or add additional context in comments.

3 Comments

That won't work. You either have to put the + outside of the brackets or--better still--not use the brackets at all. Everything inside the character class represents one character.
What about ?some_other_quantity=5&quantity=9?
thank you !! =) i have solve my problem.... it was breaking my head in the early morning =(
0
replace(/[?&]quantity=\d+([&]?)/g,"$1quantity=50$2");

try this ^


([?&])

group together either symbol '?' or '&' (one and only one char) as the group named $1

\d+

find at least one digit and find the longest consecutive string of digits if there is >1 digits

([&]?)

group together either empty string (if at the end) or '&' as the group named $2

'?' means match zero or one time

by grouping a group of match in ()...()....() and then use it in the result as $1,$2,$3... you can do search and replace plus many more complex operations.

Comments

0

Here is one way you could do it. It will only ever work with the query string, not the entire URL.

function example(){
   var quantity = 'http://www.example.com/index.php?brandid=b%123&quantity=20',
       a = document.createElement('a');

    a.href = quantity;

    a.search = a.search.replace(/([?&;]quantity=)\d+/, '$150');;

   return a.href;
}

jsFiddle.

1 Comment

anchor.search will begin with a ? so that should probably be a.search = a.search.replace(/([&^;\?]quantity=)[\d\.]+/, '$150'); Added a decimal too, just in case.

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.