Count insensitivities - Javascript

I'm currently using a counter to find occurrences of a substring within a string, but it's case sensitive. Here's my current code:

count = (string.match(new RegExp(substring, 'gm')) || []).length;

For instance, if the substring appears in the string with a different case, the count will be '0'.

Is there a way to implement a case-insensitive counter instead?

Answer №1

To convert both strings to lowercase, you can either use toLowerCase() or the i flag (but be aware of this). Unfortunately, for accents, you need to replace them individually with the base string.

var text = "AÁáéíóú";

var snippet = "AAaeiou";

var r = new RegExp("")

text = text.replace(/Á|É|Í|Ó|Ú/gi, function(acc){
    if(acc=="á") return "a"
    if(acc=="é") return "e"
    if(acc=="í") return "i"
    if(acc=="ó") return "o"
    if(acc=="ú") return "u"

    if(acc=="Á") return "a"
    if(acc=="É") return "e"
    if(acc=="Í") return "i"
    if(acc=="Ó") return "o"
    if(acc=="Ú") return "u"
})

var occurrences = (text.match(new RegExp(snippet, 'gmi')) || []).length;

console.log(occurrences)

If you also have the character ñ, you will need to handle it individually as well.

You could consider using .normalize(), but keep in mind that it does not work in IE.

var text = "AÁáéíóú";

var snippet = "AAaeiou";

var r = new RegExp("")

text = text.normalize('NFD').replace(/[\u0300-\u036f]/gi, "")

var occurrences = (text.match(new RegExp(snippet, 'gmi')) || []).length;

console.log(occurrences)

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

Playing out the REST endpoint in ExpressJS simulation

Suppose I have set up the following endpoints in my ExpressJS configuration file server.js: // Generic app.post('/mycontext/:_version/:_controller/:_file', (req, res) => { const {_version,_controller,_file} = req.params; const ...

Executing a get request in Backbone without using the Option parameter by implementing the beforeSend method

After gathering insights from the responses to this and this queries, I have formulated the code below for a GET request: var setHeader = function (xhr) { xhr.setRequestHeader("Authorization", "Basic " + btoa($rootScope.login.Gebruikersnaam + ":" + $r ...

Preventing Further Navigation When an Incorrect Password is Entered

I am struggling with preventing navigation when a user enters the wrong password in my app. Despite trying to implement an If condition, the redirection still occurs after catching the error. Here is the code snippet I have been working with: login = (em ...

The Typescript Select is displaying an incorrect value

Here's the code snippet I've been working with: <select #C (change)="changeSelect(zone.id, C.value)"> <option *ngFor="let town of townsLocal" [attr.value]="town.data" [attr.selected]="town.data === zone.town && 'selected& ...

Changing the position of an element in CSS using the center as the reference point, based on a JavaScript variable: How can it be done?

I have an image marking a scale, with the marker's position in HTML set as: <image class="red-marker" xlink:href="./assets/images/marker.png" [attr.x]=percentage width="12" height="40" y="0" ></image> But I want the middle of the marker ...

Utilize Content Delivery Network Components in Conjunction with a Command Line Interface Build

As we progress in building our Vue applications, we have been using the standard script tag include method for Vue. However, as we transition from jQuery/Knockout-heavy apps to more complex ones, the maintenance issues that may arise if we don't switc ...

The HTML view is unable to display the CSS style due to a MIME-type error

I have recently developed a very simple Express app that is supposed to display a single view called home.html from the view directory. Although the home.html file is being shown, none of the CSS styles I added seem to be loading. The console is throwing t ...

Effortlessly move and place items across different browser windows or tabs

Created a code snippet for enabling drag and drop functionality of elements within the same window, which is working smoothly. var currentDragElement = null; var draggableElements = document.querySelectorAll('[draggable="true"]'); [].forEach ...

What is the best way to utilize getInitialProps specifically during the building process of a NextJS site?

When I am developing a static site using NextJS, I need the getInitialProps method to run specifically during the build process and not when the client loads the page. During the build step, NextJS executes the getInitialProps method before generating the ...

Implementing CSS styles on selected elements using jQuery

My current HTML layout looks like this.. <div class="container> <div class="panel"> <div> <div> <div> <img class="match" src="myimage.jpg"> &l ...

Instructions for rotating a sphere simultaneously along the x, y, and z axes

Seeking assistance on how to properly rotate an image along all three axes using the Three Js library. Currently, rotation along one axis works fine, but when attempting rotation along all three axes, the results are abnormal. I have read about using quate ...

Issue with jQuery centering in IE browsers with jquery-ui-1.10.3.custom.js and jquery-ui-1.9.2.custom.js not working as expected

Are there any other alternatives you can recommend? Here is the dialog structure: <div id="dialogbox" title="message box"> <p>example content</P> </div> ...

Accessing UPI apps such as Google Pay through deep linking from a web application

I am currently exploring the possibility of deep-linking to individual UPI apps, like Google Pay, that are installed on a user's phone. The goal is for users to be seamlessly redirected to their preferred UPI app when they click on the respective icon ...

Element that emulates a different element in HTML

Is it possible to have one element that can control and change multiple clone elements, mimicking every change made to the original? While JavaScript & jQuery can easily achieve this, most solutions involve separate variables or instances for each element ...

Navigate through the elements of an Ext.form.CheckboxGroup using Ext JS

Currently, I am working with an Ext.form.CheckboxGroup that contains multiple items of Ext.form.Checkbox. I am wondering if there is a way to iterate through each item within the Ext.form.CheckboxGroup? I attempted the code below without success: for ( ...

I struggle with generating a transition effect in the input box through label transformation

Why is the input box not using the specified CSS styles for the input and label tags? The transform property doesn't seem to be working as expected. I've highlighted the areas where I'm facing issues with bold text, and I've included bo ...

What could be causing the "undefined object" warning within this optional chain?

I encountered this issue: buyTicketData?.pricingOptions resulting in this error message: [tsl] ERROR in /Applications/MAMP/htdocs/wp-content/plugins/tikex/tikexModule/components/BuyTicket/PricingOptionInvoiceItemsFormFieldsCheckboxes.tsx(280,25) TS2 ...

What is the process for creating a parent container in which clicking anywhere inside will cause a child container (built with jQuery UI draggable) to immediately move to that location?

This is a rundown of tasks that I am struggling to code more effectively: When the bar is clicked anywhere, I want the black dot button to instantly move there and automatically update the displayed percentage below it. Additionally, when I drag the butt ...

Prevent PHP Timer from resetting each time the page is refreshed

I am struggling with implementing a timer for my Quiz web application. The timer keeps resetting every time the user moves to the next question or refreshes the page. I attempted to save the remaining time to a variable, but as a beginner, I'm not su ...

Easily submit both FormData and a string in a single function call

I am trying to send data from a form (including a file input and string input) via ajax to an ASP.NET Function. When sending only files, I use the following code: function readURL() { var input = document.getElementById("fileUpload"); var files ...