![](/img/trans.png)
[英]How to replace a pattern in string with a strong tag using regex and javascript?
[英]find '*' , '**' and '`' from string and replace with <strong></strong> and <code></cod in javascript, Typescript
我們需要處理一個“字符串”並用<strong></strong>
包圍'*'和'**'之間的所有文本,以及backTic和<code> </code>
之間的文本。 現在我已經編寫了邏輯,它也運行良好,但我確信,必須有一個更好的方法,因為這個簡單的字符串處理任務的代碼太多了。 以下是我的代碼。 感謝任何建議。
input = "*within single star* and **within double start** and this is `backtick string`"
output = "<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;
不是最好的方法。 但是短代碼。
var converter = new showdown.Converter(); var input = "*within single star* and **within double start** and this is `backtick string`"; var output = converter.makeHtml(input); output = "\\"" + output + "\\"" output = output.replace(/<p>/g, "") output = output.replace(/<\\/p>/g, "") output = output.replace(/<em>/g, "<strong>") output = output.replace(/<\\/em>/g, "</strong>") console.log(output)
<script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.9.0/showdown.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.