我正在使用textarea编写这样的文本:
%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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句