2017-07-27 81 views
3

目标:用由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. 

我怎么能有效地做到这一点?

+0

你想删除什么? –

+1

不是“重复连续字符”而是“计数并替换_a特定字符_”?如果你想统计重复的连续字符,你会得到'快乐'中的'p'命中。 – msanford

+1

我有点困惑,第一个匹配'my',''name'和'a',第二个匹配'my','name','is'和'happy', ?如果它只是匹配一个名字,你怎么知道一个名字是什么? – adeneo

回答

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);

+1

这很酷,似乎也是[最快](https://jsperf.com/finding-regexyo/1)。 –

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>

2

如果你想只更换astriks你可以使用这个简单的正则表达式:

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);

输出:

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

JSFiddle:(看控制台)