如何在javascript中将单词推入数组



我想在单词之间分割,但不是在"@%5967411b349:Jean leo%"标签。

如何解决?

let title = "Hello everyone @%5967411b349:Jean leo% and @%5995006d0d:David Leong% wish you have a good day with <audi <samsung and #canon";

const formatTitle = (title) => {
const results = []
title.trim().split(" ").map(title => {
if (title.indexOf("#") === 0) {
results.push(title)
results.push(" ")
}
else if (title.indexOf("<") === 0) {
results.push(title)
results.push(" ")
}
else if((title.indexOf(title)) === 0)
{
let userTag = title.replace(/[@%]*/g, '').split(':');
results.push(title)
results.push(" ")
}
else {
results.push(`${title} `)
results.push(" ")
}
})
return results
};
formatTitle(title)

预期输出:大家好@李奥@梁朝伟祝你与<奥迪><三星和#佳能有美好的一天>

我想你是在找这个

let input = "Hello everyone @%5967411b349:Jean leo% and @%5995006d0d:David Leong% wish you have a good day with <audi <samsung and #canon";
const userTag = (str) => {
str = str.replace(/@%(.*?):(w+)s+(w+)%/g, '@$1:$2_$3');
let groups = str.match(/[@#<]?w*:?w+/g)
.map(item => (item.indexOf('@') > -1) ? item.replace('_', ' ') : item);
console.log(groups);
}
userTag(input);

这可能相当令人困惑,但regex可以很好地实现替换功能。

let string = "Hello everyone @%5967411b349:Jean leo% and @%5995006d0d:David Leong% wish you have a good day with <audi <samsung and #canon";
console.log(string.replace(/(@%[0-9a-z]{1,}:)([a-zA-Zs]{1,})(%)/g, "@$2"));

代码可能不是最终的解决方案,但可能是一个想法的开端。https://regexr.com/5lns0将演示regex当前是如何工作的。

我使用正则表达式来解决这个问题。你可以检查一下。

let title = "Hello everyone @%5967411b349:Jean leo% and @%5995006d0d:David Leong% wish you have a good day with <audi <samsung and #canon";
title = title.replace(/@Ww+:(w+sw+)%/g, "@$1");

const titleArray = title.match(/(#?<?w+)|(@w+sw+)/g);
console.log(titleArray);

最新更新