将字符替换为标记(例如 *hi* 到 <p>hi</p>)

Replace character with tags (ex. *hi* to <p>hi</p>)

本文关键字:hi 替换 字符 例如      更新时间:2023-09-26

我正在尝试用标签(<p></p>)替换每组通配符(**)。

例如,如果我有:

var stuff = array(
    "The color *blue*!!!!",
    "The color *red*!!!!",
    "The colors *red* and *blue*!!!!"
);

我想输出:

var stuff = array(
    "The color <p>blue</p>!!!!",
    "The color <p>red</p>!!!!",
    "The colors <p>red</p> and <p>blue</p>!!!!"
);
最有效的

方法是什么?

为什么不运行一个简单的循环:

for(var i=0; i < stuff.length; i++) {
   stuff[i] = stuff[i].replace(/[*]([^*]+)[*]/g, '<p>$1</p>');
}

尝试

var stuff = [
    "The color *blue*!!!!",
    "The color *red*!!!!",
    "The colors *red* and *blue*!!!!"
];

 var res  = stuff.map(function(o){
     return o.replace(/'*(.*?)'*/g,'<p>$1</p>');
 });

或者只是一个循环

 for(var i=0, len = stuff.length; i<len; i++){
      stuff[i] = stuff[i].replace(/'*(.*?)'*/g,'<p>$1</p>');
  }

小提琴