将**标题**转换为<h1>标题</h1>在一个字符串中遍历大文本

What is the best way to convert **title** to <h1>title</h1> in large text in one string traversal?

本文关键字:gt h1 lt 标题 字符串 一个 遍历 文本 转换      更新时间:2023-09-26

假设有一大段文本,转换规则为:

  • **title**<h1>title</h1>

  • :blush:<img class="emoji" title="blush" src="/img/blush.png"/>

如何在一次遍历中进行转换?

做这些事情的最好方法是regex——它是针对每种语言中的此类任务进行优化的机制。

根据您的示例:

>>> "**title** qweqwe **foo** ololo **bar**".replace(/('*'*('w+)'*'*)/g, "<h1>$2</h1>")
"<h1>title</h1> qweqwe <h1>foo</h1> ololo <h1>bar</h1>"

":blush: qweqwe :tongue: ololo :smile:".replace(/(':('w+)':)/g, '<img class="emoji" title="$2" src:="/img/$2.png"/>')
"<img class="emoji" title="blush" src:="/img/blush.png"/> qweqwe <img class="emoji" title="tongue" src:="/img/tongue.png"/> ololo <img class="emoji" title="smile" src:="/img/smile.png"/>"

塔达!

你可以试试这个:

<div id="replace">**title**some text :blush: some link </div>
var str= $("#replace").html();    
str = str.replace("**title**", "<h1>title</h1>");     
str = str.replace(":blush:", "<img class="emoji" title="blush" src:"/img/blush.png"/>");     
$("#replace").html(str);    

用不同的捕获组捕获1个正则表达式中的不同模式,并具有检查不同捕获组的替换功能:

var input = '**Hey** Oh you! :blush:';
document.write(input.replace(/'*'*([^*]*)'*'*|:(happy|blush):/ig, function(match, title, smiley) {
  if (title != undefined) {
    return '<h2>' + title + '</h2>';
  } else if (smiley != undefined) {
    return '<img class="emoji" title="blush" src="/img/' + smiley + '.png" />';
  }
}));

这是在这个页面上只有一次遍历的唯一答案。不过要注意的是,它不会捕捉到这个:

var text = '**title with :blush: smiley** gotcha!';

您可以使用正则表达式来解决此问题。

var mystring = 'some text **title** some other text';
var re = /'*{2}('w*)'*{2}/g;
mystring.replace(re, "<h1>$1</h1>");

在这里,regex搜索以2*开头、以2*结尾的任何模式。中间部分被捕获并在替换方法中使用。

标题

var re_title = /'*'*(.+)'*'*/g;
str.replace(re_title, '<h1>$1</h1>')

表情符号

var re_emoji = /:(.+):/g;
str.replace(re_emoji, '<img class="emoji" title="$1" src="/img/$1.png"/>')

你可以通过一个接一个的替换来将它们结合在一起。

str.replace(re_title, '<h1>$1</h1>').replace(re_emoji, '<img class="emoji" title="$1" src="/img/$1.png"/>')

样品

var str = '**title** :some_emoji:'
str.replace(re_title, '<h1>$1</h1>').replace(re_emoji, '<img class="emoji" title="$1" src="/img/$1.png"/>')
// output = "<h1>title</h1> <img class="emoji" title="some_emoji" src="/img/some_emoji.png"/>"
var str = '**:some_emoji: **'
str.replace(re_title, '<h1>$1</h1>').replace(re_emoji, '<img class="emoji" title="$1" src="/img/$1.png"/>')
// output = "<h1><img class="emoji" title="some_emoji" src="/img/some_emoji.png"/></h1>"

由于无法命名捕获组,因此不能使用"a|b"regex语法进行替换。