如何解析html textarea输入的特殊变量

问题描述 投票:0回答:2

[我希望用户在他们的文本区域提交中使用一个特殊的变量来表示某人的名字,例如字符串{name},现在我该如何使用PHP或JS解析该textarea输入,以将{name}转换为实际名称,并不按字面意思使用{name}?

javascript php
2个回答
0
投票
这样的东西?我创建了一个函数putContent,如果要用[>替换很多{name}, {last_name},请在其中输入要替换的值]

const textareaStr = '{first_name} is my name, and ${last_name} is my last name'; const firstName = 'Naruto'; const lastName = 'Uzumaki'; let newStr = textareaStr; newStr = putContent(newStr, 'first_name', firstName); newStr = putContent(newStr, 'last_name', firstName); console.log(newStr); function putContent(str,key, value) { return str.replace(new RegExp(`{${key}}`, 'g'), value); }

0
投票
您可以使用str_replace代替所有出现的{name}。即
© www.soinside.com 2019 - 2024. All rights reserved.