gpt4 book ai didi

javascript 匹配替换文本

转载 作者:行者123 更新时间:2023-11-28 11:13:42 24 4
gpt4 key购买 nike

简单的问题,我有一些 Markdown HTML 内容,我想将其从双星号转换为粗体。

我收到的错误是:`Uncaught TypeError: Cannot call method 'replace' of null '

这是 jsfiddle:http://jsfiddle.net/fz5ZT/9/

这是 HTML:

<div class="comments">comment 1** is good**</div>
<div class="comments">comment 2**is bad**</div>

这是 JS:

function markdown(markdownable){

var boldMatch = markdownable.match(/\*\*[A-Za-z0-9]+\*\*/gim),
boldReplace = boldMatch.replace(/\*\*[A-z0-9]+\*\*/gim, '<span style="font- weight:bold;color:blue;">'+boldMatch+'</span>'),
markdownable = markdownable.replace(boldMatch, boldReplace),
markdownable = markdownable.replace(/\*\*/gi, "");

return markdownable;
}

$('.comments').each(function(){
var markdownable=$(this).html(), comments=markdown(markdownable);
});

如果您能提供帮助,我将不胜感激,

谢谢,蒂姆

更新谢谢大家!请参阅此工作演示:http://jsfiddle.net/fz5ZT/30/

最佳答案

markdownable = markdownable.replace( /\*\*(.+?)\*\*/gm, '<strong>$1</strong>' );

然而,与其进行半心半意、善意的、注定会失败的重新发明轮子的尝试,为什么不直接use an existing JavaScript Markdown library呢? ?

编辑:这是一个更强大的正则表达式,它(如 Markdown)要求“打开”之后或“关闭”之前没有空格:

var bold = /\*\*(\S(.*?\S)?)\*\*/gm;
markdownable = markdownable.replace( bold, '<strong>$1</strong>' );

关于javascript 匹配替换文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10233204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com