2017-07-27 6 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特定の文字_を置き換えますか?"重複する連続した文字を数えたい場合、 '' happy''の 'p'のヒットを得るでしょう。 – msanford

+1

私はちょっと混乱しています。最初のものは 'my'、' name'と 'a'で一致し、2番目のものは' 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:(コンソールを見て)

関連する問題