Make every letter uppercase in the regex match - null, [...], and [...,...]

I have developed a regular expression that identifies all instances of two-letter words. The results can either be null or an array with an unknown number of items.

const regex_all_two_letter_words = /(\b\w{2}\b)/g;
var regexCapitalize = /[A-Z]+/g;

// inputs
const testString = [
    "j handcock",
    "je handcock",
    "jim handcock",
    "jim j handcock",
    "jim je handcock,",
    "jim jer handcock",
    "j handcock",
    "j. e, handcock",
    "j. er handcock jr",
    "jim js handcock sr",
    "jim handcock nn",
];

testString.forEach((str) => {
    var test = str.match(regex_all_two_letter_words);
    console.log(test);
});

Results:

null
[ 'je' ]
null
null
[ 'je' ]
null
null
null
[ 'er', 'jr' ]
[ 'js', 'sr' ]
[ 'nn' ]

I am attempting to capitalize both letters and replace any lowercase variants with uppercase versions.

This is my current approach:

    /// Inside the forEach function
    var finalStr = function (test) {
        if (test !== null) {
            var text = test.replace(regexCapitalize);
            return text;
        }
        return text;
    };

(This returns various functions)

Thank you!

Answer №1

const sampleTexts = [
    "j handcock",
    "je handcock",
    "jim handcock",
    "jim j handcock",
    "jim je handcock,",
    "jim jer handcock",
    "j handcock",
    "j. e, handcock",
    "j. er handcock jr",
    "jim js handcock sr",
    "jim handcock nn",
]
console.log(
  sampleTexts.map(text=>text.split(' ')
    .map(item=>item.replaceAll(/[^a-z]/ig,'').length===2?item.toUpperCase():item)
    .join(' '))
)

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

handlebars.js template to check the condition based on the last item in an array

I am currently utilizing handlebars.js as my templating engine and am interested in creating a conditional segment that will only display if it happens to be the final item within an array located in the templates configuration object. { columns: [{< ...

JavaScript Update Function for Pointers in Parse.com - Modify a Row with a Pointer

I am currently working with Parse and JavaScript. While I know the ObjectId from the Status_id-class, I am facing a challenge in updating the column in the Question_status-class due to it being of Pointer-type. Can anyone guide me on how to update a Poin ...

Error message encountered while attempting to search on Wikipedia: "Unable to connect to *ngFor" (Angular2 / HTML / Javascript)

I am currently working on developing a search bar that will search through data and display the results based on the input in the search box after clicking a button. The data can be sourced from Wikipedia or local fake data, it doesn't make a differen ...

Is there a way to identify consecutive sets of identical elements within a list?

I am in need of creating a function that takes a list of integers L and an integer n. The goal is to determine if the list contains a consecutive sequence of ones with a length of n, returning True if it does, and False otherwise. For example, let's ...

Unable to utilize ng-Bootstrap datepicker

I recently cloned the quickstart project from the tour of heroes guide on Angular's official website, and I wanted to incorporate the ng-Bootstrap datepicker. However, I encountered some issues with its functionality. Below are the key components of m ...

Create JavaScript variable from either HTML or database sources

Hello, I am trying to implement a counter that retrieves its value from a JavaScript file, but I would like to customize it. Below is the JavaScript code: function updateCounter(count) { var divisor = 100; var speed = Math.ceil(count / divisor); ...

Using curly braces when invoking a function from HTML within a Vue.js application

When I call a function, for example on click, it works whether or not I use curly braces. However, I have created a function that triggers a custom event from a child component. I then await this event in a parent component and update the state with my par ...

The Javafx WebEngine's executescript() function is unable to send a multiline string

Issue: I'm struggling to make the JavaFX WebEngine trigger a JavaScript function when using a Java String object with multiple lines. If I input the following example in HTML: "asd" ENTER "qwe" into the textArea, and then click the send button, the f ...

I am facing difficulties with invoking the popOpen() function within my parameters in JS, HTML, and CSS

I'm currently facing an issue with my code. I am attempting to invoke my openPop() function with the input parameter 'pop' within some of my sensor code, but no pop-up is appearing even though I believe I am calling the popup correctly. If a ...

Encountering a build error with Ubuntu, Node-Gyp, and Canvas – help needed!

Hey there, I'm having some trouble with installing the Canvas package. I've tried Package Versions 6.1.13 and 6.1.3 Here are my system details: Ubuntu 18.04.5, Node 12.18.4 LTS, Python 2.7, g++ installed, pkg-config installed, libjpeg installed ...

What is the best way to show the HTML content inside a foreach loop when the array is empty?

The code snippet below is functional when the $getbanking variable contains data. However, an error occurs if $getbanking is empty: Warning : Invalid argument supplied for foreach() in It is necessary to execute the following code at least once if $getb ...

How to Monitor Store Changes within a Vue File Using Vue.js

I am working with 2 vue files, header.vue and sidebar.vue. Both components are imported into layout.vue. Here are the steps I am following: 1. Initially, when the page loads, I update the store in header.vue with some values inside the created hook. 2. ...

Using Jasmine and ReSharper to test TypeScript modules

In my VS2017 project, I have a Jasmine test written in TypeScript: describe("A simple test", () => { it("Should succeed", () => { expect(true).toBeTruthy(); }); }); Everything runs smoothly using the ReSharper test runner. However, when I ...

Unexpected discovery about Immediately Invoked Function Expressions (IIFE) in Node.js on Windows operating

Have you encountered this behavior while using nodejs? It seems a bit buggy to me, but could it be expected? What am I missing here? var abc = function(){ console.log("hello"); } (function(){ console.log("welcome"); })(); When I run this code, I enc ...

Leveraging XSL for presenting KML data within an interactive HTML table

It has been a while since I last delved into coding, so I appreciate your patience... I have an application that generates the following non-standard kml file: <?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://www.opengis.net/kml/2.2"> ...

How can I deactivate a Material UI button after it has been clicked once?

Looking to make a button disabled after one click in my React project that utilizes the MUI CSS framework. How can I achieve this functionality? <Button variant="contained" onClick={()=>handleAdd(course)} disabled={isDisabled} > ...

Learn how to efficiently execute a function multiple times using pure JavaScript

I am trying to create a tabbed content functionality with multiple elements. How can I utilize the same function for various elements declared in a variable? For example, I want to clone the parent div.tabs element with similar content but different ids an ...

I am interested in using the split method to separate and then mapping an object in JavaScript

Need assistance on separating an array using the split method. The array contains objects with properties such as name, course1, course2, and course3. Only the courses with text in their content along with a plus sign should be separated into an array usin ...

Engaging with the CSS content attribute

Below is a code snippet that inserts an image before the header tag. Is there a way to incorporate JavaScript or jQuery in order to execute certain actions when the inserted image is clicked? h1::before { content: url(smiley.gif); } The HTML code fo ...

Trouble receiving Ajax response

Below is the code snippet I am working on: function f(){ var value = ""; var request1 = $.ajax({ url : '/a', type: "GET" }); var request2 = $.ajax({ url: '/b', type: ...