替换文本以进行降价或格式化

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

我想将

*hello*
替换为 hello 我该怎么做?和相同但有其他前缀

let content = '*Hello*, my **friend** how are you?'

      function formatString(content) {
        let step1 = content.split(" ").join(" ").replaceAll("\n\n", "</br></br>");
        //replace
      }
      formatString(content)//should return '<i>Hello</i>, my <b>friend</b> how are you?'

我尝试使用正则表达式,但我只能将

*string*
替换为 string 而不是 string

javascript html
2个回答
0
投票

使用正则表达式 /*(.?)*/g 的 replaceAll 方法用 string 替换所有出现的 string,和 /**(.?)**/g 替换所有出现的 string string。 g 标志确保所有出现的地方都被替换,而不仅仅是第一个。

let content = '*Hello*, my **friend** how are you?'

function formatString(content) {
  let step1 = content.split(" ").join(" ").replaceAll("\n\n", "</br></br>");
  let step2 = step1.replaceAll(/\*(.*?)\*/g, "<i>$1</i>");
  let step3 = step2.replaceAll(/\*\*(.*?)\*\*/g, "<b>$1</b>");
  return step3;
}

console.log(formatString(content))


-1
投票

您可以使用 ShowdownJS 库 处理 Markdown 到 HTML 的转换。

let content = '*Hello*, my **friend** how are you?';
const converter = new showdown.Converter();
let res = converter.makeHtml(content);
console.log(res);
<script src="https://unpkg.com/showdown/dist/showdown.min.js"></script>

© www.soinside.com 2019 - 2024. All rights reserved.