如何在 JavaScript 中用正则表达式替换字符串

How can an string be replaced in JavaScript with regex

本文关键字:正则表达式 替换 字符串 JavaScript      更新时间:2023-09-26

如何在 Javascript 中用正则表达式替换字符串?

一个特定的正则表达式现在困扰着我。我只想替换字符串中的count=15,例如:

countryNo=-1&count=15&page=2

我怎样才能得到如下格式:

countryNo=-1&count=**20**&page=2

countryNo=-1&count=**30**&page=2

我尝试了以下方法:

var x = 'countryNo=-1&count=15&page=2';
x = x.replace('count='d{2}', 'count=30');

什么也没发生。我怎样才能让它工作?

使用正则表达式文本,而不是字符串文本:

x = x.replace(/count='d{2}/, 'count=30');

参考:正则表达式上的 MDN

顺便说一句,您可能是干燥的,您不必重复"count="

x = x.replace(/(count=)'d{2}/, '$130');

您将正则表达式指定为字符串。用:

x = x.replace(/count='d{2}/, 'count=30');

从字符串文本中删除正则表达式

尝试以下

x = x.replace(/count='d{2}/, 'count=30');