Check if there are two or more identical characters repeated and return true

I've experimented with several regular expressions, including the ones below:

      1> var pattern = "(.)\\1{2,}";
      2> var pattern = "^(?!.*(.)\\1{2,})";

       regexExp = new RegExp(pattern);

When I test them, this is the output I receive:

  regexExp.test("sss is true")
  regexExp.test("ss is false")
  regexExp.test("sdsdsd is false") //instead of being true.

My regular expressions only consider consecutively repeated characters and not others.

Answer №1

You can include .* before \1 (to match any 0+ characters except line breaks) and utilize this regex pattern:

/(.)(?:.*\1){2,}/

Alternatively, if the input string may contain line breaks:

/([\s\S])(?:[\s\S]*\1){2,}/

Refer to the example of this regex. In JavaScript regex, [\s\S] (or [^]) matches any character, while . excludes line break characters.

About the Method

  • (.) - captures any single character
  • (?:.*\1){2,} - signifies two or more consecutive instances of:
    • .* - represents any sequence of characters excluding line breaks
    • \1 - refers back to the value captured in Group 1 (same character)

Answer №2

Consider this example:

let phrase = "hello world";
let hasRepeatedLetters = (/([a-zA-Z]).*?\1/).test(phrase);
console.log("Phrase contains repeated letters: ", hasRepeatedLetters);

Answer №3

let word = 'abcdeaf';
if (word.match(/(.).*\1/) {} else {}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reloading a page in Vue-Router after submitting a form

Learning Vue by creating a movie searcher has been quite challenging. The issue I'm facing is that I'm using the same component for different routes with path params to fetch specific information. However, when I submit a form with a query for t ...

jQuery Ajax request encounters error when trying to access correct URL

I am facing a challenge while trying to access a REST Web Service from an HTML/JavaScript application. I have set up both the web application and the Web Service on Apache HTTPD 2.2 server. Interestingly, when I directly call the Web Service's GET met ...

Using React JS to iterate over an array and generate a new div for every 3 items

It's a bit challenging for me to articulate my goal effectively. I have a JSON payload that looks like this: { "user": { "id": 4, "username": "3nematix2", "profile_pic": &qu ...

The error message "[Insecure URL]" was triggered at line 85 of angular.min.js in the AngularJS framework

Looking for some assistance with Angular as I have limited knowledge. It was working fine on localhost, but after upgrading from PHP5 to PHP7, I encountered this error: angular.min.js:85 Error: [$sce:insecurl] http://errors.angularjs.org/1.2.13/$sce/inse ...

Guide to transferring/managing information to/from a form using jquery

I am currently in the process of constructing some new posts and they can be linked to a file, task, or event. Therefore, I have included a section for each attachment type in my new_post_form. My inquiry is regarding how to prevent data submission if the ...

Save the content from the page into a variable using JavaScript/jQuery

Is there a way to store the output of the_content() into a variable? Here is what I have attempted: <script type="text/javascript"> window.the_content = "<?php the_content(); ?>"; </script> Additionally, I tried this method: <?p ...

In Angular 8 Router, the original parent route will remain unchanged even when navigating to a route with a different parent route

I'm currently developing a project using Angular version 8.2.8 and implementing routing with the same version. The structure of the routing is as follows: Within my app-routing.module.ts, I have defined 3 entries in the routes array: Shell.childRoute ...

Utilizing Selenium to add a JavaScript event listener will automatically activate it

After conducting thorough research, I've discovered that there is no direct way to capture user input using Selenium. In an attempt to work around this limitation, I have implemented a JavaScript event listener. Unfortunately, upon executing the code ...

The functionality of ng-show is not functioning properly in a handsontable column

I'm currently utilizing Handsontable 0.34.5 alongside AngularJS 1.6.5 and the ngHandsontable 0.13 wrapper. My requirement is to hide a column in the handsontable table based on a certain condition. I attempted to achieve this using the ng-show or ng ...

employ the inverse Euler application

var a = new THREE.Euler( 0, 1, 1.57, 'YXZ' ); var b = new THREE.Vector3( 1, 0, 1 ); var c = b.applyEuler(a); In order to get the value of c using b.applyEuler(a), I am looking for the reverse operation involving applyEuler. Given that the value ...

What is the reason that in Node/Express, you are unable to pass the response object to a helper function for tasks like validation in order to prevent the ERR_HTTP_HEADERS_SENT error from

My web app is built using Node (v.18.2) and Express (v. 4.18). Users can make POST requests, which I validate upon arrival. If a user makes an error, I send back an error message to inform them of what went wrong. In order to streamline this process, I de ...

Toggling panel and sub-panel controls in AngularJS

In my project, which is a CV builder with front-end editing capabilities, I have multiple panels and sub-panels (DIVs) that I need to show their controls on click in order to perform specific tasks. Currently, my approach for show/hide panels is very basic ...

Extract information from a JSON string stored in a variable and transform it into objects within the $scope.variable

I currently have a string variable that contains JSON data displayed below. var jsonstring = [{"latitude":"51.5263","longitude":"-0.120285","altitude":"","device":"123","rating":"5","region":"Europe","customer":"","time":"1-2 Weeks","error":"Error 1","app ...

Expand the capabilities of a jQuery plugin by incorporating new functions or modifying existing ones

I have a task to enhance the functionality of a jQuery Plugin (https://github.com/idiot/unslider) by adding another public method. (function(){ // Store a reference to the original remove method. var originalMethod = $.fn.unslider; // Define a ...

Having trouble passing data from JavaScript to PHP with AJAX

I attempted to use AJAX to send data from an array (emp) and other string variables like 'gtotal' in my code, but the data did not transfer to the PHP file. Despite no errors being shown, when I removed the isset() function it displayed an error ...

Having difficulty completing the text field and submitting it automatically

My goal is to automatically fill in the "Reason for Access" text box with the word "TEST" using Tampermonkey. I am new to using Tampermonkey and UserScript, so I appreciate your patience. Currently, I am facing an issue where the "Reason for Access" field ...

What is the best way to add a "Submit" button to a JavaScript/HTML calculation form?

I'm looking to integrate a "Submit" button that triggers the formula execution upon clicking, but I'm struggling to establish the connection between the submit button and the code so that the total emissions only update when the button is activat ...

Update $(img).offset() upon clicking and dragging the image

Whenever I click on an image, it moves to a random position. I want different sounds to play based on where the click occurs: Directly on the image Within 50px of the image More than 50px away from the image. To achieve this, I need to constantly updat ...

Steps to activate a faded background following a form submission triggered by an On change event

My goal is to implement a greyed-out background upon form submission without a traditional submit button. Instead, I want the form to be submitted when the user selects an option from one of three drop-down lists. Here is a snippet of the form: <form ...

Is there a way to compel the browser or JavaScript to delete/disregard a cached file?

I've encountered an issue with my Javascript program that extracts data from a text file and displays it in a table. The problem arises when I update the text file - the changes don't reflect on the table because the browser is caching the file. ...