jquery,将部分文本输入解析为格式化的html输出?

标签 jquery regex parsing input textarea

我正在查看非常少量的代码:

var val = $("#id_input").val();
$("#output").text(val);

这本质上是将输入输入到一个字段中,<textarea id="id_input"></textarea> ,并按原样输出。

我想做的是转入以 - 开头的输入换行符进入输出<ul><li></li></ul>在我的网站上....

我一直在采用的方法是按行分割输入,然后在将每一行传递通过之后将它们连接起来:

function startsWith(string, pattern) {
  return string.slice(0, pattern.length) == pattern;
}

show(startsWith("-"));

我觉得有更标准的方法吗?例如,我读过 StackOverflow 上使用 find 的其他帖子。函数产生类似的结果。我对这些表示怀疑,因为没有真正的正则表达式。这似乎好得令人难以置信。

enter image description here

在图像中,您可以看到绿色文本是 comments ,白色文字为input ,黑色文字为output .

我知道现有技术具有此功能,但它们还具有许多其他功能。我正在尝试创建一个隔离此功能的输入。

最佳答案

uls = val.replace(/(^-.*$(?:\n^-.*$)*)/mg, "<ul>\n$1\n</ul>")
lis = uls.replace(/^-(.*)$/mg, '<li>$1</li>')
$("#output").html(val);

this你在找什么?它并不完美,但它完成了基础工作。

其工作原理如下:

Surround the would be lists with <ul></ul>
    This works by finding lines that start with a '-' |^-.*$|,
    then matching contiguous, similar lines |(?:\n^-.*$)| 0 or more times |*|
    it uses the multiline (m) and global (g) flags too:
      match ^ and $ at the begining and end of lines (m)
      and get all the ones in the string (g)
    surround them (<ul>\n$1\n</ul>)
Surround the list items with <li></li>
     match lines with a hyphen at the beginning |^-(.*)$|
     surround them (<li>$1</li>)

关于jquery,将部分文本输入解析为格式化的html输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13041255/

相关文章:

javascript - 检查输入的格式和值

regex - 数据框列上的 Spark scala 模式匹配

使用pyparsing进行SQL解析

javascript - 为什么内联元素底部有额外的边距?

javascript - onchange输入框只允许数字和一个点

javascript - jquery中点击的两个函数

java - 为什么这个转换会出错呢?

ios - Swift 4+SwiftyJson 自动从 JSON 转换/生成对象

javascript - Select2 关闭事件触发后聚焦输入

javascript - Jquery 日期选择器选择突出显示的月份