问题描述
尝试在javascript中解析一个字符串,该字符串包含标记为*multi word bold*
(星号)的粗体注释和标记为_multi word italic_
(下划线)的斜体注释.我希望解析器功能支持多个单词注释,粗体中的斜体,斜体中的粗体和混合(请参见示例).
Trying to parse a string in javascript that contains bold annotations, marked as *multi word bold*
(asterisk), and italic annotations, marked as _multi word italic_
(underline).
I'd like the parser function to support multi words annotations, italic within bold, bold within italic and mixed (see examples).
以下是一些带有必需输出示例的输入:
Here are some inputs with required outputs examples:
const simpleInput = "The *quick brown fox* jumps _over the lazy dog_";
const simpleOutput =[
{text: 'The '},
{text: 'quick brown fox', bold: true},
{text: ' jumps '},
{text: 'over the lazy dog', italic: true}
];
const italicWithinBoldInput = "The *quick brown _fox jumps_ over the* lazy dog";
const italicWithinBoldOutput =[
{text: 'The '},
{text: 'quick brown ', bold: true},
{text: 'fox jumps', bold: true, italic: true},
{text: ' over the', bold: true},
{text: ' lazy dog'}
];
const mixedInput = "The *quick brown _fox jumps* over the_ lazy dog";
const mixedOutput =[
{text: 'The '},
{text: 'quick brown ', bold: true},
{text: 'fox jumps', bold: true, italic: true},
{text: ' over the', italic: true},
{text: ' lazy dog'}
];
我在npm上尝试了一些解析器,但是一切都有些过头了,我所需要的完全没有.
I tried some parsers on npm but everything was a bit of an overkill, nothing was quite what I needed..
推荐答案
您可以通过以下方式完成
You can do it in the following way
function getObject(str){
let bold = false, italics = false;
let output = [];
let text = str.split('').reduce((a, b) => {
if(b == '*'){
if(bold){
if(a != ''){
if(italics)
output.push({text: a, bold: true, italics:true});
else
output.push({text: a, bold: true});
}
bold = false;
}
else{
if(italics)
output.push({text: a, italics: true})
else
output.push({text: a})
bold = true;
}
return '';
}
else if(b == '_'){
if(italics){
if(a != ''){
if(bold)
output.push({text: a, bold: true, italics:true});
else
output.push({text: a, italics: true});
}
italics = false;
}
else{
if(bold)
output.push({text: a, bold: true})
else
output.push({text: a})
italics = true;
}
return '';
}
else{
return a+b;
}
}, '');
if(text != '')
output.push({text : text});
console.log(output);
return output;
}
const simpleInput = "The *quick brown fox* jumps _over the lazy dog_";
getObject(simpleInput);
const italicWithinBoldInput = "The *quick brown _fox jumps_ over the* lazy dog";
getObject(italicWithinBoldInput);
const mixedInput = "The *quick brown _fox jumps* over the_ lazy dog";
getObject(mixedInput);
这篇关于js-将markdown字符串(仅粗体和斜体)解析为文本+样式jsons数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!