gpt4 book ai didi

javascript - 从字符串中找到 '*' 、 '**' 和 '` 并替换为
转载 作者:行者123 更新时间:2023-11-30 11:02:01 24 4
gpt4 key购买 nike

我们需要处理一个“字符串”,并用 <strong></strong> 包围“*”和“**”之间的所有文本。和 backTic 与 <code> </code> 之间的文本类似.现在我已经编写了逻辑,它也能正常工作,但我相信,一定有更好的方法,因为对于这个简单的字符串处理任务来说,代码太多了。以下是我的代码。感谢任何建议。

输入 = "*within single star* and **within double start** and this is `backtick string`"

输出 = "<strong>within single star</strong> and <strong>within double start</strong> and this is <code>backtick string</code>"

transform(data: any) {
if (data) {
const processDblStar = (input) => {
const regExforDoubleStar = /(\*\*)+/gi;
let i = 0;
const result = input.replace(regExforDoubleStar, (match, matchedStr, offset) => {
i++;
return i % 2 === 0 ? '</strong>' : '<strong>';
});
return result;
};

const processSingleStar = (input) => {
const regExforSingleStar = /(\*)+/gi;
let i = 0;
const result = input.replace(regExforSingleStar, (match, matchedStr, offset) => {
i++;
return i % 2 === 0 ? '</strong>' : '<strong>';
});
return result;
};

const processBackTick = (input) => {
const regExforBackTick = /(\`)+/gi;
let i = 0;
const result = input.replace(regExforBackTick, (match, matchedStr, offset) => {
i++;
return i % 2 === 0 ? '</code>' : '<code>';
});
return result;
};

const processPipeline = (functions) => (inputStr) => functions.reduce((result, fn) => fn(result), inputStr);

const funcArr: Function[] = [];
if (data.indexOf('`') >= 0) {
funcArr.push(processBackTick);
}
if (data.indexOf('*') >= 0) {
funcArr.push(processSingleStar);
}
if (data.indexOf('**') >= 0) {
funcArr.push(processDblStar);
}

processPipeline(funcArr)(data);
}
}

最佳答案

您可以使用正则表达式对 ** 之间的所有文本进行分组和 * .使用此组,您可以通过使用 $1 引用它来在替换字符串中使用它.我们也可以用反引号做同样的事情,但是,相反,将匹配的组包围在 <code></code> 中。标签。

const str = '*within single star* and **within double start** and this is `backtick string`';

const proccessPipeline = s =>
s.replace(/\*{1,2}(.*?)\*{1,2}/g, '<strong>$1</strong>')
.replace(/`(.*?)`/g, '<code>$1</code>');

const res = proccessPipeline(str);
console.log(res);
document.body.innerHTML = res;

关于javascript - 从字符串中找到 '*' 、 '**' 和 '` 并替换为 <strong></strong> 和 <code></cod in javascript, Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57352478/

24 4 0

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