![](/img/trans.png)
[英]Replace all occurrences of html tags and special unicode character from a string
[英]Replace a specific character from a string with HTML tags
有一个文本输入,如果有一个特定的字符,它必须把它转换成一个标签。 例如,特殊字符是*
,2 个特殊字符之间的文本必须以斜体显示。
例如:
This is *my* wonderful *text*
必须转换为:
This is <i>my</i> wonderful <i>text</i>
所以我尝试过:
const arr = "This is *my* wonderful *text*";
if (arr.includes('*')) {
arr[index] = arr.replace('*', '<i>');
}
它用<i>
替换星号,但如果有更多特殊字符则不起作用。
有任何想法吗?
您可以简单地创建wrapper
,然后使用正则表达式来检测是否有任何被*
包围的单词,然后简单地将其替换为任何标签,在您的示例中是<i>
标签,因此请参见以下内容
let str = "This is *my* wonderful *text*"; let regex = /(?<=\\*)(.*?)(?=\\*)/; while (str.includes('*')) { let matched = regex.exec(str); let wrap = "<i>" + matched[1] + "</i>"; str = str.replace(`*${matched[1]}*`, wrap); } console.log(str);
你去吧,我的朋友:
var arr = "This is *my* wonderful *text*"; const matched = arr.match(/\\*(?:.*?)\\*/g); for (let i = 0; i < matched.length; i++) { arr = arr.replace(matched[i], `<i>${matched[i].replaceAll("*", "")}</i>`); } console.log(arr);
首先解释一下,我们通过设置 /g 匹配正则表达式全局注意:与全局标志匹配的匹配返回一个数组。 其次,我们正在寻找位于两个星号之间的任何字符,我们正在转义它们,因为它们都是元字符。 .*? 以贪婪的方式匹配所有内容,这样我们就不会得到这样的东西my *. ?: 对于非捕获组,我们将替换与自身匹配但没有星号的每个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.