javascript - 如何制作自定义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 中一样使用数组和调用一次替换来实现这一点,那么替换的想法会太多。
解决方案
您可以用字符串替换函数,并$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)
推荐阅读
- python - 如何在pygame中移动多个对象而不影响其他对象的运动(无延迟)
- python - Django 中 Celery 任务的问题,因未知原因停止
- python - 使用 Python 多处理池时消耗大量内存
- python - 使用 Pandas 从 csv 文件制作行向量
- node.js - Mongoose:如果没有数据字段,则无法从 .chunk 集合中获取文件文档
- javascript - 在 fetch json 中使用变量
- javascript - 如何根据某些条件动态渲染两层元素
- html - HTML/CSS:在同一水平线上允许网站的导航栏和标题出现问题
- python - 如何中断调用 shell 脚本的 Python 程序?
- python - 从 cmd 加载 jupyter-lab 时收到错误是否有任何解决方案