首页 > 解决方案 > 如何制作自定义bbcode?

问题描述

我正在尝试创建一个带有几个标签的自定义 bbcode:粗体、斜体、罢工和下划线,就像 whatsapp 一样。目前,我正在这样做但并不完美:

var bold=/\*(.*?)\*/gi
var italise=/_(.*?)_/gi

var data='**Bold this* and _italise this_';

data=data. replace(bold,function(m,text){
   return '<strong>' + text + '</strong>';
  }).replace(italise,function(m,text){
   return '<i>' + text + '</i>';
  });

如果有 * * Bold this * but this * Bold this * 有效,这并不优雅,也不会加粗文本

而且我觉得如果我可以像在 php 中一样使用数组和调用一次替换来实现这一点,那么替换的想法会太多。

标签: javascript

解决方案


您可以用字符串替换函数,并$1用于第一个捕获的组:

var bold = /\*([^*]+)\*/gm
var italise = /_([^_]+)_/gm

var data = '*Bold this* and _italise this_'

data = data.replace(bold, '<b>$1</b>').replace(italise, '<i>$1</i>')

console.log(data)
document.write(data)

编辑:要获得您正在寻找的效果,您需要为此定义一个函数。

String.prototype.replaceMultiple = function () {
  let v = this;
  [...arguments].forEach(arg => (v = v.replace(arg[0], arg[1])));
  return v;
}

let str = '*Bold this* and _italise this_ and **strikethrough** another *bold*   **strikethrough2** and _italic!_'
let newStr = str.replaceMultiple(
  [/(?<!\*)\*([^*]+)\*(?!\*)/gm, '<b>$1</b>'], // Bold
  [/_([^_]+)_/gm, '<i>$1</i>'], // italic,
  [/\*\*([^*]+)\*\*/gm, '<s>$1</s>'] // strikethrough
)
console.log(str)
console.log(newStr)


推荐阅读