正则表达式替换为小的文本更改?

问题描述 投票:0回答:1

我需要将一些HTML内容转换为UBB代码,例如将

<>
符号替换为方括号
[]

还可能有一个

<ol>
标签,其
start=
属性指定标记的类型。

const str = `<b>Something</b> is going on.<br><i>But what?</i><br><br><ol start="3"><li>First</li><li>Second</li><li>Third</li></ol>`;
const regex = new RegExp(`<(\/?([bisu]|li|ul|ol|ol start="\d+"))>`);
let result = str.replace(/0/gi, '').match(regex);

这按预期工作,但我想删除引号,因此

<ol start="3">
将变为
[ol start=3]
。我想知道这在同一个正则表达式中是否可能。

javascript html regex
1个回答
0
投票

你可以尝试这样做

const str = `<b>Something</b> is going on.<br><i>But what?</i><br><br><ol start="3"><li>First</li><li>Second</li><li>Third</li></ol>`;

// replace all angle brackets with square brackets
let result = str.replace(/</g, "[").replace(/>/g, "]");

//  remove unnecessary quotes around the 'start' attribute value
res = result.replace(/\[ol start="(\d+)"\]/gi, "[ol start=$1]");

console.log(res);

资源

[b]Something[/b] is going on.[br][i]But what?[/i][br][br][ol start=3][li]First[/li][li]Second[/li][li]Third[/li][/ol]
© www.soinside.com 2019 - 2024. All rights reserved.