JavaScript中的字符串替换(如查询绑定)



感谢您回答我的问题,我认为这不是插值,所以我更改了标题,在您用JavaScript将其标记为重复为字符串插值之前,请仔细阅读问题,因为我已经阅读了JavaScript的另一个插值问题,但其中没有一个问题与我想要的代码有相同的方式(我告诉了问题的原因(,我不想使用插件。

大家好,首先我想让你们知道我在这段代码中的目的,你们可以告诉我,主要原因是用MySQL为Express构建查询绑定,但我也会出于其他原因使用这段代码。

我想知道Javascript/Typescript中的字符串插值,它将像代码点火器源中的代码中的查询绑定一样工作

// Code 1
let person = 'ujang'
let age = 23
console.log("Hello, %s. You're age is %d years old.", person, age)
// Hello, ujang. You're age is 23 years old.
// The function is similiar to this code
// $sql = "insert into tbl_user (name, age, groupname) values (?, ?, ?)";
// $this->db->query($sql,array('codeigniter, 35, 'Group 1'));

正如你在上面的代码中看到的那样,我使用console.log,它按照我想要的方式工作,但由于console.log是无效的,没有返回任何值,我无法在实际情况下使用它。

// Code 2
const str = 'helow, %s. and you want %d piece of cake.?'
const name = 'ujang'
const want = 13
const myFunction = (value, ...optionalParams) => {
// The function I want is similiar with Query Binding in Code Igniter
// And it can handle dynamicly params
// This only sample
value = value.replace('%s', optionalParams[0])
value = value.replace('%d', optionalParams[1])
return value
}
myFunction(str, name, want)
// helow, ujang. and you want 13 piece of cake.?

在代码2中,我将尝试创建一个函数,该函数按预期工作,但仅适用于静态参数。

// Code 3
const names = 'ujang'
const arg1 = 'good' 
const argN = 'better'
const dontWantFunction = (value, arg1, argN) => {
return `helow, ${value}, this function is ${arg1} but any ${argN} solution.?`
}
dontWantFunction(names, arg1, argN)
// helow, ujang, this function is good but any better solution.?

在代码3中,我并不真正想要这个函数,因为它很难管理,而且函数中有更多的硬编码文本。

有人知道如何在Code 2中填写myFunction吗。?

或者任何研究类似代码的人。?

或者知道一些文档/文章,将引导我找到这个解决方案。?

我正在等待你的回复,这将对我有很大帮助,感谢您的关注。

您可以尝试这样的操作,我们以顺序的方式从optionalParams中取出值,并替换匹配的值

const str = 'helow, {{value}}. and you want {{value}} piece of cake.?'
const name = 'ujang'
const want = 13
const myFunction = (value, ...optionalParams) => {
return value.replace(/{{value}}/g, (m) => optionalParams.shift() || m)
}
console.log(myFunction(str, name, want))

最新更新