检查段落是否以字符开头,如果是,则对其应用 HTML 样式



我正在使用文本区域来编写这样的文本:

%this is my text
%%also text
simple text
%%%last text

如果一个段落以%开头,它应该用<h1>显示整行,如果有2,%%,它应该是<h2>的,依此类推,直到<h3>

对于上面的示例,它必须返回:

<h1>this is my text</h1>
<h2>also text</h2>
simple text
<h3>last text</h3>

我已经这样做了:

var result = inputVal.replace('%', '<h1>');

它替换了开头的符号,但我不知道如何在行尾添加结束标签。以及如何计算有多少%以便它可以显示,或其他。

这是一种方法吗?

function convertToTags(textToConvert) {
// the current text.
const str = textToConvert
// get me the number of the tags.
const tagsCount = str.split("").filter(x => x === "%").length
// if no hash signs return the result
if (tagsCount === 0) return textToConvert;
// give me the text without the tags
const text = str.replaceAll("%", "")
// tie all the pieces together.
const result = `<h${tagsCount}>${text}</h${tagsCount}>`
return result;
}
console.log(convertToTags("%this is my text"))
console.log(convertToTags("%%also text"))
console.log(convertToTags("simple text"))
console.log(convertToTags("%%%last text"))

这将适用于 h1 到 hn。

// the current text. 
const str = '%%%last text'
// get me the number of the tags.
const tagsCount = str.split("").filter(x => x === "%").length
// give me the text without the tags
const text = str.replaceAll("%", "")
// tie all the pieces together.
const result = `<h${tagsCount}>${text}</h${tagsCount}>`

您可以将该代码包装在函数中

function convertToTags(textToConvert) {
// the current text.
const str = textToConvert
// get me the number of the tags.
const tagsCount = str.split("").filter(x => x === "%").length
// if no hash signs return the result
if (tagsCount === 0) return textToConvert;
// give me the text without the tags
const text = str.replaceAll("%", "")
// tie all the pieces together.
const result = `<h${tagsCount}>${text}</h${tagsCount}>`
return result;
}

也许您可以遍历所有行并在每次迭代中重新生成字符串。

演示:

var inputVal = `%this is my text
%%also text
simple text
%%%last text`;
inputVal = inputVal.split('n').map(function(v){
if(v.trim() && v.startsWith('%')){
var c = v.split(' ')[0].match((/%/g) || []).length;
v = `<h${c}>${v.substring(c)}</h${c}>`;
}
return v;
}).join('n');
console.log(inputVal);

最新更新