我想用自定义字符替换用户输入的一些单词。字符串将是这样的
var userInput = "five plus five equal to ten multiply 5";
这是我想做的
const punctLists = {
name: 'star',
tag: '*'
},
{
name: 'bracket',
tag: ')'
}, {
name: 'multiply',
tag: '*'
}, {
name: 'plus',
tag: '+'
}, {
name: 'double equals',
tag: '=='
}, {
name: 'equal',
tag: '='
}]
var matchPunction = punctLists.find(tag => tag.name == userInput);
if (matchPunction) {
userInput = matchPunction.tag;
}
但它不起作用。 我想要这样的东西:
var userInput = "5+5 = 10*5";
有什么想法吗?
最佳答案
var userInput = "five plus five equal to ten multiply 5";
const punctLists = [
{ name: "star", tag: "*" },
{ name: "bracket", tag: ")" },
{ name: "multiply", tag: "*" },
{ name: "plus", tag: "+" },
{ name: "double equals", tag: "==" },
{ name: "equal", tag: "=" },
{ name: "five", tag: "5" },
{ name: "ten", tag: "10" }
];
console.log(userInput
.split(' ')
.map(x => (f = punctLists.find(item => item.name == x)) && f.tag || x)
.join(' '))
关于javascript - 替换字符串中的多次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56771245/