2017-07-27 21 views
3

Ziel: Ersetzen Sie aufeinanderfolgende Sternchen durch die Anzahl von ihnen umgeben von der sup Tag.Ersetzen Sie das Zeichen durch die Anzahl

Eingang

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. 

Ausgabe

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. 

Wie könnte ich dies effizient erreichen?

+0

Welche Duplikate möchtest du entfernen? –

+1

Nicht "doppelte aufeinanderfolgende Zeichen" sondern "zählen und ersetzen _ ein bestimmtes Zeichen_"? Wenn Sie doppelte aufeinanderfolgende Zeichen zählen möchten, erhalten Sie einen Treffer für die 'p's in' happy'. – msanford

+1

Ich bin ein wenig verwirrt, würde nicht die erste Übereinstimmung auf 'my',' name' und 'a' treffen, und die zweite würde auf' my', 'name',' is' und 'happy' passen ? Wenn es nur einem Namen entsprechen soll, woher weißt du dann, wie ein Name ist? – adeneo

Antwort

3

Sie können einen regulären Ausdruck mit replace verwenden und die Callback-Funktion die Länge des Spiels zählen:

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

Demo:

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

Das ist cool, scheint auch [schnellste] zu sein (https://jsperf.com/finding-regexyo/1). –

3

Hier ist eine sehr einfache Implementierung. Manche mögen es rohe Gewalt nennen, aber ich denke, es ist mehr Seelenfrieden.

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

Wenn Sie nur ersetzen möchten astriks Sie diese einfache RegExp verwenden können:

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

Ausgang:

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

JSFiddle: (Blick auf die Konsole)

Verwandte Themen