用计数替换字符

时间:2017-07-27 19:00:05

标签: javascript jquery replace

目标:将连续的星号替换为sup标记所包围的计数。

输入

Hello, my name is Chris Happy*. My profile picture is a happy face.**

*: It's not my actual name, but a nickname.
**: Well, my "last name" is happy, so I think it's fitting.

输出

Hello, my name is Chris Happy<sup>1</sup>. My profile picture is a happy face.<sup>2</sup>

<sup>1</sup>: It's not my actual name, but a nickname.
<sup>2</sup>: Well, my "last name" is happy, so I think it's fitting.

我怎样才能有效地完成这项工作?

3 个答案:

答案 0 :(得分:3)

这是一个非常简单的实现。有些人可能称之为蛮力,但我认为这更安心。

var string = `Hello, my name is Chris Happy*. My profile picture is a happy face.**
*: It's not my actual name, but a nickname.
**: Well, my "last name" is happy, so I think it's fitting.`;

// Loop through the total string length because it may consist of only duplicates.
for (var i = string.length; i > 0; i--)
      string = string.replace(new RegExp("\\*{" + i + "}", "g"), "<sup>" + i + "</sup>");
// Display the string
document.getElementById('output').innerHTML= string;
<span id="output"></span>

答案 1 :(得分:3)

您可以使用带有replace的正则表达式,并且回调函数可以计算匹配的长度:

txt = txt.replace(/\*+/g, m => `<sup>${m.length}</sup>`);

演示:

var txt = `Hello, my name is Chris Happy*. My profile picture is a happy face.**

*: It's not my actual name, but a nickname.
**: Well, my "last name" is happy, so I think it's fitting.`;

txt = txt.replace(/\*+/g, m => `<sup>${m.length}</sup>`);

console.log(txt);

答案 2 :(得分:2)

如果您只想替换astriks,可以使用这个简单的RegExp:

&#13;
&#13;
var str = "Hello, my name is Chris Happy*. My profile picture is a happy face.**";
str = str.replace(/(\*)+/g, rep);

function rep(matches) {
  return '<sup>' + matches.length + '</sup>';
}
console.log(str);
&#13;
&#13;
&#13;

输出:

 Hello, my name is Chris Happy<sup>1</sup>. My profile picture is a happy face.<sup>2</sup>.

JSFiddle :(查看控制台)