javascript 在Javascript中检测字符串中的重复字母
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20513274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect repeating letter in an string in Javascript
提问by Pavi
code for detecting repeating letter in a string.
用于检测字符串中重复字母的代码。
var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z])+$/).test(str)
alert("repeating string "+hasDuplicates);
I am getting "false"as output for the above string "paraven4sr". But this code works correctly for the strings like "paraaven4sr".i mean if the character repeated consecutively, code gives output as "TRUE". how to rewrite this code so that i ll get output as "TRUE"when the character repeats in a string
我得到“ false”作为上述字符串“ paraven4sr”的输出。但是这段代码对于像“ paraaven4sr”这样的字符串可以正常工作。我的意思是如果字符连续重复,代码输出为“真”。如何重写此代码,以便当字符在字符串中重复时我将输出为“ TRUE”
回答by MT0
var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z]).*?/).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; then\1+
- immediately following it one or more copies of that letter; then$
- the end of the string.
([a-zA-Z]])
- 它在第一组中捕获的字母;然后\1+
- 紧随其后的是该信件的一份或多份副本;然后$
- 字符串的结尾。
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; then.*?
- zero or more characters (the?
denotes as few as possible); until\1
- it finds a repeat of the first matched character.
([a-zA-Z])
- 它在第一组中捕获的字母;然后.*?
- 零个或多个字符(?
表示尽可能少);直到\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.
如果您要求第二个匹配项必须在字符串$
的末尾,那么您可以添加到正则表达式的末尾,但是从您想要的文本描述中,这似乎没有必要。
回答by Ringo
回答by Jonatas Walker
To just test duplicate alphanumeric character (including underscore _
):
只测试重复的字母数字字符(包括下划线_
):
console.log(/(\w)+/.test('aab'));
回答by Christian
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 ;)
编辑:对不起,只是读到你不是在搜索一个函数来查找一个字母是否被多次找到,而是查找一个字母是否重复。无论如何,我把这个功能留在这里,也许它会有所帮助。对不起 ;)