替换 javascript 中的一些字符串

Replace some string in javascript

var x="45ab6eb6f099e866a97a10famount%5D=7.00";

我需要替换amount%5D=之后的值。即我需要制作 ...amount%5D=56.00

主要是amount%5D前后的字符串一直在变

即可能是

sdd45ab6eb6f099e866a97a10famount%5D=4.00
gdfgdtgtrrtamount%5D=3.00

有几种方法可以做到这一点:

1:正则表达式:

x.replace(/(.+%5D=).+/, '' + yourNewValue);

2:字符串拆分:

var parts = x.split('%5D=');
var newString = parts[0] + '%5D=' + yourNewValue;

一个简单的解决方案是使用 replace(regExp, 'replacement')。下面是一个快速示例,说明如何使用匹配模式 /amount%5D=[0-9]+.[0-9]+/.

的正则表达式对 x 和 x1 执行此操作
// test with first variable
var x="45ab6eb6f099e866a97a10famount%5D=7.00";
var y = x.replace(/amount%5D=[0-9]+.[0-9]+/, "amount%5D=235.00");
console.log(y)
var y = x.replace(/amount%5D=[0-9]+.[0-9]+/, "amount%5D=12.00");
console.log(y)
var y = x.replace(/amount%5D=[0-9]+.[0-9]+/, "amount%5D=11.00");
console.log(y)

// test with new variable
var x1="dsf45ab6eb6f099e866a97amount%5D=7.00";
var y = x1.replace(/amount%5D=[0-9]+.[0-9]+/, "amount%5D=235.00");
console.log(y)
var y = x1.replace(/amount%5D=[0-9]+.[0-9]+/, "amount%5D=12.00");
console.log(y)
var y = x1.replace(/amount%5D=[0-9]+.[0-9]+/, "amount%5D=11.00");
console.log(y)

输出

45ab6eb6f099e866a97a10famount%5D=235.00
45ab6eb6f099e866a97a10famount%5D=12.00
45ab6eb6f099e866a97a10famount%5D=11.00
dsf45ab6eb6f099e866a97amount%5D=235.00
dsf45ab6eb6f099e866a97amount%5D=12.00
dsf45ab6eb6f099e866a97amount%5D=11.00

您可以对正则表达式进行更多限制(例如,只允许 2 位小数)。此表达式仅用于说明目的。