gpt4 book ai didi

javascript - 从具有特定元素的动态字符串创建数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:54:13 25 4
gpt4 key购买 nike

我有一个字符串“你好@steph 你请求的电子邮件是用户@test 的test@test.com”

我想把它变成:

['hello ', <a href="">@steph</a>, 'the email you requested is test@test.com for user ', <a href="">@test</a>];

这是我所拥有的:

function matchUserMention(text) {
var pattern = /\B@[a-z0-9_-]+/gi;
return text.match(pattern); // [@steph, @test]
}

function applyUser(string) {
let text = string;
if (typeof text != 'string') return text;
var arr = [];

function replaceAll(str, find, replace) {
return text.replace(new RegExp(find, 'g'), replace);
}
const matches = matchUserMention(text);
_.each(matches, (match) => {
text = replaceAll(text, match, <a href={'https://test.co'}>${match}</a>);
});
return text;
}

现在返回的文本:

'hello <a href="">@steph</a>, the email you requested is test@test.com for user <a href="">@test</a>

有人知道从这里创建数组的最佳方法吗?它不能太重,因为我需要一直调用它

最佳答案

function applyUser(string) {
const reg = /\B@[a-z0-9_-]+/ig;
const res = [];
let match;

// loop while we can match something
while((match = reg.exec(string)) !== null) {
// push to result array portion of string before user match, if any
if (match.index > 0) {
res.push(string.substring(0, match.index));
}

// push updated user name to result array
res.push('<a href="">' + match[0] + '</a>');

// remove processed part from a string
string = string.substr(match.index + match[0].length);
}

// push any reminder to the result array
if (string) {
res.push(string);
}
return res;
}

关于javascript - 从具有特定元素的动态字符串创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41577661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com