2017-07-27 124 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:(看控制檯)