在JavaScript中替换几个匹配的匹配项

时间:2016-03-17 21:38:14

标签: javascript

大家好我写了一个代码来改变我的字符串颜色,这些颜色带有标签,如(^ 0,^ 1,^ 2,^ 3,...,^ 9) 我用PHP做了但我很困惑我可以用JavaScript做同样的功能吗?

$host = "^5MY ^4Team ^2Name ^8Is ^6LOL";

function getColoredName($host){
    $count_rpl = 0;
    $hostname = $host;
    $h2 = str_replace("^1","<div style='color:#FF0000;'>", $hostname, $count_rpl_1);
    $h3 = str_replace("^2","<div style='color:#00FF00;'>", $h2, $count_rpl_2);
    $h4 = str_replace("^3","<div style='color:#FFFF00;'>", $h3, $count_rpl_3);
    $h5 = str_replace("^4","<div style='color:#0000FF;'>", $h4, $count_rpl_4);
    $h6 = str_replace("^5","<div style='color:#00FFFF;'>", $h5, $count_rpl_5);
    $h7 = str_replace("^6","<div style='color:#FF00FF;'>", $h6, $count_rpl_6);
    $h8 = str_replace("^7","<div style='color:#FFFFFF;'>", $h7, $count_rpl_7);
    $h9 = str_replace("^0","<div style='color:#000000;'>", $h8, $count_rpl_8);
    $final = str_replace("^8","<div style='color:#000000;'>", $h9, $count_rpl_9);
    $count = $count_rpl_1 + $count_rpl_2 + $count_rpl_3 + $count_rpl_4 + $count_rpl_5 + $count_rpl_6 + $count_rpl_7 + $count_rpl_8 + $count_rpl_9;
    $final = $final . str_repeat("</div>", $count);
    return $final;
}

我如何在JavaScript中执行相同的功能,如果有可能有人为我做同一个,谢谢?

<script>
function getColoredName(input) {
    if (input != undefined)

    ....

}
</script>

2 个答案:

答案 0 :(得分:2)

使用.replace()应该很有趣

&#13;
&#13;
var text = "^5MY ^4Team ^2Name ^8Is ^6LOL but most of all ^999StackOverflow rules!!";

var sym2clr = {
  "^0": "#000",
  "^1": "#f00",
  "^2": "#0f0",
  "^3": "#ff0",
  "^4": "#00f",
  "^5": "#0ff",
  "^6": "#f0f",
  "^7": "#fff",
  "^8": "#000",
  "^999": "#f48024"
};

var html = text.replace(/(\^\d+)([^\^\s]+)/g, function(_1, $2, $3){
  return "<span style='color:"+ sym2clr[$2] +"'>"+ $3 +"</span>";
});

document.body.innerHTML = html;
&#13;
&#13;
&#13;

如果您希望仅对一个号码进行说明,请使用d代替d+

随意改进上述正则表达式:https://regex101.com/r/sD9vW1/1

答案 1 :(得分:0)

String.prototype.replace()

第一个arg是要在其调用的字符串中匹配的模式或子字符串。查看文档以获得更高级的用法。