[英]JavaScript replace single quote with HTML code tag
我有以下字符串,并试图用 HTML 代码标签替换它。
var stringdata = "Hello world, this is a `sample` string. Here is some CSS code for the string `.typetext{ color:#000; }`";
预期 Output:
Hello world, this is a <code>sample</code> string. Here is some CSS code for the string <code>.typetext{ color:#000; }</code>
我正在使用下面的代码,但它只是用with code tag and not wrapping the content inside the
stringdata=stringdata.replace(/(`)/ig, "<code>$1</code>");
您可以根据计数替换'`'(如果它是一个结束标签,如果它是一个开始标签)
const stringdata = "Hello world, this is a `sample` string. Here is some CSS code for the string `.typetext{ color:#000; }`"; const {str: replaced} = stringdata.split("").reduce((lookup, c) => { let {count, str} = lookup if(c==='`'){ count++ str += count % 2? '<code>': '</code>' return {count, str} } return {...lookup, str: str + c} }, { count: 0, str: "" }) console.log(replaced)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.