[英]Detect repeating letter in an string in Javascript
code for detecting repeating letter in a string. 用于检测字符串中重复字母的代码。
var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z])\1+$/).test(str)
alert("repeating string "+hasDuplicates);
I am getting " false" as output for the above string " paraven4sr ". 我得到“ 假”作为上述字符串“ paraven4sr ”的输出。 But this code works correctly for the strings like " paraaven4sr". 但是这段代码可以正常地用于像“ paraaven4sr”这样的字符串。 i mean if the character repeated consecutively, code gives output as " TRUE" . 我的意思是如果角色连续重复,代码将输出设为“ TRUE” 。 how to rewrite this code so that i ll get output as " TRUE" when the character repeats in a string 如何重写此代码,以便当字符在字符串中重复时输出为“ TRUE”
var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z]).*?\1/).test(str)
alert("repeating string "+hasDuplicates);
The regular expression /([a-zA-Z])\\1+$/
is looking for: 正则表达式/([a-zA-Z])\\1+$/
正在寻找:
([a-zA-Z]])
- A letter which it captures in the first group; ([a-zA-Z]])
- 它在第一组中捕获的一个字母; then 然后 \\1+
- immediately following it one or more copies of that letter; \\1+
- 紧跟其后的一封或多份副本; then 然后 $
- the end of the string. $
- 字符串的结尾。 Changing it to /([a-zA-Z]).*?\\1/
instead searches for: 将其更改为/([a-zA-Z]).*?\\1/
而不是搜索:
([a-zA-Z])
- A letter which it captures in the first group; ([a-zA-Z])
- 它在第一组中捕获的一封信; then 然后 .*?
- zero or more characters (the ?
denotes as few as possible); - 零个或多个字符( ?
表示尽可能少的字符); until 直到 \\1
- it finds a repeat of the first matched character. \\1
- 它找到第一个匹配字符的重复。 If you have a requirement that the second match must be at the end-of-the-string then you can add $
to the end of the regular expression but from your text description of what you wanted then this did not seem to be necessary. 如果您要求第二个匹配必须位于字符串结尾处,那么您可以将$
添加到正则表达式的末尾,但是根据您想要的文本描述,这似乎没有必要。
要测试重复的字母数字字符(包括下划线_
):
console.log(/(\w)\1+/.test('aab'));
Something like this? 像这样的东西?
String.prototype.count=function(s1) {
return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}
"aab".count("a") > 1
EDIT: Sorry, just read that you are not searching for a function to find whether a letter is found more than once but to find whether a letter is a duplicate. 编辑:对不起,只是看到你没有找到一个函数来查找是否多次找到一个字母,但要查找一个字母是否重复。 Anyway, I leave this function here, maybe it can help. 无论如何,我把这个功能留在这里,也许它可以帮助你。 Sorry ;) 对不起;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.