-2

I have a string that contains URL like parameters:

var params="f5=212&f1=255&f3=400&f6=789&f9=243"

I want to change the value of f1, say from 255 to 355.

But the problem is parameters are dynamic and location of individual parameter changes. Below are possible cases:

var params="f1=456&f5=212&f3=400&f6=789&f9=243"
var params="f5=212&f1=451&f3=400&f6=789&f9=243"
var params="f5=212&f3=400&f1=255&f6=789&f9=243"
var params="f5=212&f3=400&f6=789&f9=243&f1=123"

How can I create the regex to change f1 value correctly by JavaScript?

Jessie
  • 175
  • 1
  • 1
  • 7

2 Answers2

4

You can capture what is immediately before f1:

params = params.replace(/(^|&)f1=[^&]*/, '$1f1=355');
Casimir et Hippolyte
  • 83,228
  • 5
  • 85
  • 113
0

You can use this regex:

var new_var = 355;
params = params.replace(/f1=[0-9]{3}/,'f1='+new_var);   
n-dru
  • 9,039
  • 2
  • 25
  • 39