简体   繁体   中英

Regexp Javascript replacing

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

replace(/quantity=[\d]+/g,"quantity=50")

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM