感谢您回答我的问题,我认为这不是插值,因此我更改了标题,在将其标记为JavaScript中的字符串插值重复项之前,请仔细阅读该问题,因为我已经阅读了JavaScript的另一个插值问题,但没有它们具有与我的代码相同的方式(我告诉了问题的原因),并且我不想使用插件。
大家好,首先,我想让您了解我在此代码中的用途,您可以说出这个主要原因是为了使用MySQL构建Express的查询绑定,但是我还将出于其他原因使用此代码。
我想了解Javascript / Typescript中的字符串插值,其工作方式类似于Code Igniter源代码中的查询绑定
// 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中,我并不是真正想要的功能,因为它很难管理并且在功能内有更多的硬编码文本。
是任何人都知道如何填写myFunction
在Code 2
?
或从事类似代码工作的任何人。
或知道一些文档/文章将引导我使用此解决方案。
我正在等待您的答复,这将对我有很大帮助。谢谢您的关注。
您可以尝试类似的方法,在该方法中,我们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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句