Regexp replace Javascript

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 link with quantity=50 . but I tried some regex like:

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

so I would like some help from the regex experience to help me =) thanks

+4
source share
3 answers
 replace(/quantity=[\d]+/g,"quantity=50") 
+3
source

Here is one way to do it. It will only work with the query string, not the full 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 .

0
source
 replace(/[?&]quantity=\d+([&]?)/g,"$1quantity=50$2"); 

try this ^


 ([?&]) 

group together or the character '?' , or '&' (one and only one char) as a group named $ 1

 \d+ 

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

 ([&]?) 

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

'?' means zero or one match

grouping a group of matches into () ... () .... (), and then use it as a result as $ 1, $ 2, $ 3 ... you can search and replace, plus many more complex operations.

0
source

Source: https://habr.com/ru/post/1391368/


All Articles