gpt4 book ai didi

javascript - 如何用不同的字符替换出现的相同字符

转载 作者:行者123 更新时间:2023-11-30 09:28:18 25 4
gpt4 key购买 nike

我有一个像这样的字符串:

my_str = "select * from users where id = ? and name = ?;"

我还有一个数组来替换'?'

var arr = [1,'test']

我想先更换?与 1 和第二?在“测试”中jQuery/JavaScript 动态。可以有多个 ?在字符串中。

注意这个问题与MySQL无关,我写的查询只是一个字符串。

最佳答案

对于更动态的选项,其中 replace 是一个包含顺序替换的数组:

const string = 'select * from users where id = ? and name = ?;'
const replace = [1, 'test']

let index = 0
const output = string.replace(/\?/g, () => replace[index++])
console.log(output)

关于javascript - 如何用不同的字符替换出现的相同字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48002187/

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