gpt4 book ai didi

javascript - 使用具有两个变量的正则表达式替换字符串

转载 作者:行者123 更新时间:2023-12-02 18:00:45 26 4
gpt4 key购买 nike

我需要使用正则表达式值替换来替换两个字符串,因此生成的字符串是 $?tlang=es&text=Hello world,所以我不知道在这里使用 String.prototype.replace() .

const value = "Hello world"
const queryString = "?tlang=es&text=$1"

在此场景中,valuequeryString 是硬编码的,但在“现实生活”中,它应该是正则表达式组捕获的结果,如 line.match(/msgid\"(.*)\"/) 其中 line 是迭代文本行,queryString 是用户提交的内容。

我以为我可以做到这一点,但也许有更好的解决方案(我找不到)需要付出太多的努力:

const line = "Full name: John Doe" // text input
const sourcePattern = /Full name: (.*) (.*)/ // user input
let queryString = 'name=$1&lname=$2' // user input
const matches = line.match(sourcePattern)
matches.splice(0, 1)

for (let i = 0; i < matches.length; i++) {
queryString = queryString.replace(`\$${i+1}`, matches[i])
}

有什么想法吗?

最佳答案

正则表达式可以很好地从第一个字符串中提取值。但是对于使用查询字符串,有一个 built in class这有帮助:

const entries = [...new URLSearchParams(queryString).entries()]

if (matches.length !== entries.length) {
// handle error
}

const replaced = entries.reduce((params, [key], index) => {
params.append(key, matches[index]);
return params;
}, new URLSearchParams());

您可以对其调用toString()来获取修改后的查询字符串。一般来说,只要有现成的更丰富的数据类型,您就希望避免进行字符串处理。

关于javascript - 使用具有两个变量的正则表达式替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74503898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com