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

里奥·梅西

我正在使用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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如果是这样,则该样式规则在类上

检查两行是否以相同字符开头,如果是,则输出平均值,如果不是,则打印实际值

检查X = Y,如果是,则在Z div上使用CSS

检查单元格是否在范围内,如果是,则在 Excel VBA 中返回单词“Marginal”

声明不带const的C样式字符串是否不好?如果是这样,为什么?

检查字符串中的字符是否为整数,如果是,则获取该 int

检查字符串数组是否包含值,如果是,则获取其位置

jQuery检查父元素中是否包含特定文本,如果是,则在特定的预先存在的子元素之后添加子元素

Excel:检查列A是否具有特定值,如果是,则在该值所在的行中显示另一个单元格

在 VBA for Word 中从多个样式段落的开头删除字符

检查字符串是否在文件中,如果是,则替换包含该字符串的特定行

pandas 将函数应用于系列,检查前 n 个字符是否与预定义的字符串值匹配,如果是,则需要更新现有值

PyDict_SetItem是否增加键的引用计数,如果是,则在代码中的何处发生?

乘飞机的乘客是否使用分叉,如果是,则在何处设置after_fork配置?

Web服务是否应记录响应数据(如果是,则在哪个级别)?

检查用户是否已经登录,如果是则跳过

检查文件是否为存档;如果是,请提取

Rails Model方法检查字段是否为nil,如果是,则返回空字符串

检查字符串是否包含数组,如果是,则将数组中的值输出到新变量中

检查字符串中每个单词之间的空格是否超过1个,如果是,则返回负数

如果是PUT或DELETE请求,则在任何http请求上都会发生“连接重置”

检查段落的首字符是否小写

引用样式语言“如果是”

delete []是否可以与通用数组一起正常使用?如果是这样,为什么在其上使用std :: vector :: erase会导致释放内存时出错

如果不存在,则在字符串开头添加子字符串(php)

检测元素的innerHTML的最终字符是否为“ 1”,如果是,则在下划线处使最后一个字符变为绿色,并在前面添加一些文本

Angular ngIf 检查变量是否以组件 html 中的指定字符开头

检查div是否应用了特定样式

rs.EOF = True是否可行?如果是,则在vb6.0中可以在哪种情况下使用?