在Javascript中检测字符串中的重复字母 [英] Detect repeating letter in an string in Javascript

查看:125
本文介绍了在Javascript中检测字符串中的重复字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检测字符串中重复字母的代码.

code for detecting repeating letter in a string.

var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z])\1+$/).test(str)        
alert("repeating string "+hasDuplicates);

我得到false"作为上述字符串paraven4sr"的输出.但是这段代码对于像paraaven4sr"这样的字符串可以正常工作.我的意思是如果字符连续重复,代码输出为TRUE".如何重写此代码,以便在字符在字符串中重复时将输出为TRUE"

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

推荐答案

JSFIDDLE

var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z]).*?\1/).test(str)        
alert("repeating string "+hasDuplicates);

正则表达式 /([a-zA-Z])\1+$/ 正在寻找:

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.

如果您要求第二个匹配项必须在字符串的末尾,那么您可以将 $ 添加到正则表达式的末尾,但从您的文本描述中想要,那么这似乎没有必要.

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.

这篇关于在Javascript中检测字符串中的重复字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆