Replace character with graph
Purpose : Replace consecutive asterisks by counting their surroundings with a tag sup
.
Input
Hello, my name is Chris Happy*. My profile picture is a happy face.**
*: It not my actual name, but a nickname.
**: Well, my "last name" is happy, so I think it fitting.
Output
Hello, my name is Chris Happy<sup>1</sup>. My profile picture is a happy face.<sup>2</sup>
<sup>1</sup>: It not my actual name, but a nickname.
<sup>2</sup>: Well, my "last name" is happy, so I think it fitting.
How could I effectively accomplish this?
+3
source to share
3 answers
You can use a regular expression with replace
, and the callback function can count the length of the match:
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 not my actual name, but a nickname.
**: Well, my "last name" is happy, so I think it fitting.`;
txt = txt.replace(/\*+/g, m => `<sup>${m.length}</sup>`);
console.log(txt);
+3
source to share
Here's a very simple implementation. Some may call it brute force, but I think it's more calm.
var string = `Hello, my name is Chris Happy*. My profile picture is a happy face.**
*: It not my actual name, but a nickname.
**: Well, my "last name" is happy, so I think it 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>
+3
source to share
If you only want to replace astriks, you can use this simple RegExp:
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);
Output:
Hello, my name is Chris Happy<sup>1</sup>. My profile picture is a happy face.<sup>2</sup>.
JSFiddle : (look at the console)
+2
source to share