Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 用计数替换字符_Javascript_Jquery_Replace - Fatal编程技术网

Javascript 用计数替换字符

Javascript 用计数替换字符,javascript,jquery,replace,Javascript,Jquery,Replace,目标:用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</su

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

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.
你好,我叫克里斯·哈皮1。我的个人资料照片是一张快乐的脸 1:不是我的真名,是个外号。 他说:嗯,我的“姓”很高兴,所以我觉得它很合适。
我如何才能有效地完成这项工作?

这里是一个非常简单的实现。有些人可能会称之为暴力,但我认为这更能让人心平气和

var string=`你好,我叫克里斯·哈皮*。我的个人资料照片是一张快乐的脸**
*:这不是我的真名,而是一个昵称。
**:嗯,我的“姓”很高兴,所以我觉得它很合适;
//循环整个字符串长度,因为它可能只包含重复项。
对于(var i=string.length;i>0;i--)
string=string.replace(新的RegExp(“\\*{”+i+“}”,“g”),“+i+”);
//显示字符串
document.getElementById('output')。innerHTML=string

您可以将正则表达式与
replace
一起使用,回调函数可以计算匹配的长度:

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

var txt=`你好,我叫克里斯·哈皮*。我的个人资料照片是一张快乐的脸**
*:这不是我的真名,而是一个昵称。
**:嗯,我的“姓”很高兴,所以我觉得它很合适;
txt=txt.replace(/\*+/g,m=>`${m.length}`);

console.log(txt)如果只想替换Astrik,可以使用以下简单的RegExp:

var str=“你好,我的名字是克里斯·哈皮*。我的个人资料照片是一张笑脸。**”;
str=str.replace(/(\*)+/g,rep);
功能代表(匹配项){
返回“”+匹配项。长度+“”;
}

console.log(str)要删除哪些重复项?不是“重复连续字符”,而是“计数并替换特定字符”?如果你想数一数重复的连续字符,你会在
happy
中找到
p
。我有点困惑,第一个匹配的不是
my
name
a
,第二个匹配的是
my
name
is
happy
?如果它只需要匹配一个名字,你怎么知道名字是什么?