Searching for a regular expression pattern that can identify a match when a colon is present within both sets of double curly brackets

I want to optimize the method below by using regex instead of indexOf:

hasMatch(value: any): boolean {
    if (isDefined(value)) {
      const valueStr = JSON.stringify(value);
      return valueStr.indexOf('{{') > -1 && valueStr.indexOf(':') > -1;
    } else {
      return false;
    }
  }

The current implementation checks for double brackets "{{" and a colon in the string, which sometimes flags matches on colons outside of the replacement strings.

However, I only want to identify a match if a colon exists between two double brackets indicating key/value pairs like: {{key:value}}

Here is my attempt at using regex based on some examples I found (I am quite new to regex):

const matches = valueStr.match(/\{{({^\}{}*)}}/g).map(x => `[${x.replace(/[^:]/g, '')}]`)

But I am currently facing an error:

main.js:66071 ERROR TypeError: Cannot read properties of null (reading 'map')

Answer №1

To extract key-value pairs enclosed in double curly braces with a colon delimiter, you can utilize a regular expression that searches for a colon between {{ and }}, allowing for any non-} characters in between:

const data = "{{name: John}}"
console.log(data.match(/\{\{[^}]*:[^}]*}}/) !== null)

Answer №2

When considering the permitted characters for the key and value, it is important to note that both the key and value cannot be empty strings:

{{\s*\w+\s*:\s*\w+\s*}}

Check out the Regex demo here

Alternatively, a more stringent version can be used which does not match whitespace characters:

{{\w+:\w+}}

View the enhanced Regex demo here

To effectively match a key and a value, ensuring that neither the key nor the value includes any of the following: {, }, or :

{{[^{}:]*[^\s{}:][^{}:]*:[^{}:]*[^\s{}:][^{}:]}}

The pattern above matches the following components:

  • {{: Literally matching these characters
  • [^{}:]*: Matching optional characters other than {, }, or :
  • [^\s{}:]: Matching a non-whitespace character other than {, }, or :
  • [^{}:]*: Matching optional characters other than {, }, or :
  • :: Matching a colon
  • [^{}:]*[^\s{}:][^{}:]*: Highlighting the same pattern as before the colon
  • }}: Literally matching these characters

See the detailed Regex demo here

const regex = /{{[^{}:]*[^\s{}:][^{}:]*:[^{}:]*[^\s{}:][^{}:]*}}/;
[
  "{{key:value}}",
  "{{ key : value }}",
  "{{ke#$%$%y:val#!$#$^$%^$%^^%$*&%ue }}",
  "{{:}}",
  "{{key:}}",
  "{{key: }}",
  "":value}}",
  "{{key:value:test}}"
].forEach(s =>
  console.log(`${s} --> ${regex.test(s)}`)
)

Answer №3

If you're looking to achieve this task (my console didn't pick up on the syntax of your function), you can utilize the function below:

const findMatch = function (text) {
    return text.match(/\{\{([^:]*):([^:}]*)\}\}/) !== null;
}

I've included a breakdown of the regular expression since you mentioned that you're new to it.

^      // indicates the start of the input
\{\{   // looks for two consecutive curly braces 
[^:]*  // matches zero or more characters that are not colons
:      // signifies a colon
[^:}]* // matches zero or more characters that are not colons or closing curly braces
\}\}   // finds two consecutive closing curly braces
$      // marks the end of the input

findMatch("{{key:value}}")  // true
findMatch("{{:}}")          // true
findMatch("{{key:va:lue}}") // false (extra colon)
findMatch("{{key value}}")  // false (no colon separator)
findMatch("{{key,value}}")  // false (no colon separator)
findMatch("{{key:value}")   // false (only one leading curly brace)
findMatch("{key:value}}")   // false (only one trailing curly brace)
findMatch("{{}}")           // false (no colon separator)

Additional Information:

  • This regex assumes that the value does not include }.
  • If your keys and values consist only of characters, you can use \w* instead of [^:]* and [^:}]*.
  • If keys/values may contain white space, utilize [^:\s]* and [^:\s}]*.
  • If keys and values cannot be empty, replace * with +.
  • In JSON format, the key and value would be enclosed in quotation marks. This function will still correctly identify them in that scenario.

Answer №4

Utilize the {{([^:]+):([^}]+)}} regular expression to extract key-value pairs, separating the key and value into three distinct groups.

const result = "{{key: value}}".match(/\{\{([^:]+):([^}]+)\}\}/);
console.log(result);

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

Save instantly while modifying an element

I am exploring the idea of incorporating an automatic save feature using javascript/jQuery. In my project, I have multiple instances (hundreds) of elements with ids starting with `overlay-rotation-bounding-box`. For instance, `overlay-rotation-bounding-bo ...

Using ES6 Promises with jQuery Ajax

Trying to send a post request using jQuery with an ES6 promise: Function used: getPostPromise(something, anotherthing) { return new Promise(function(resolve, reject) { $.ajax({ url: someURL, type: 'post', contentType: &a ...

css based on the current time in the United States

I have a working code that currently reads the user's computer time, but I specifically need to get the hours from the USA regardless of the user's location. The CSS should be applied based on USA time. <script type="text/javascript"> dat ...

Tips for adjusting the height of a table in Semantic UI

Currently, I am utilizing semantic-ui-react, however, I am also willing to consider responses pertaining to semantic-ui exclusively. The issue I am facing is with a paginated table. The last page, which may contain fewer rows, ends up having a different h ...

What is the method for inserting a loop into a print template?

There is a print method available: printData(data): void { console.log(data); let printContents, popupWin; popupWin = window.open(); popupWin.document.write(` <html> <head> <title>Print tab</title> ...

Send the value of a JavaScript variable to a PHP file upon calling a JavaScript function

When a script button is clicked, a javascript function runs. The function looks like this: //script function oyCrosswordFooter.prototype.update = function(){ var buf = ""; if (!this.puzz.started){ buf += "Game has not ...

Is there a way to translate IBM floating point data into JavaScript numbers?

I am interested in extracting data from a legacy file format that utilizes IBM floating point numbers. These numbers were commonly used on the IBM System/360 mainframe computer system. Now, I am hoping to leverage this information within a JavaScript progr ...

Determining the Presence of an Entry in a Database Using Sequelize

Is there a way to verify if a specific ID exists in the database using Sequelize with Node.js? function checkUniqueId (id) { db.Profile.count({ where: { id: id } }) .then(count => { if (count != 0) { return false; } ...

Error in Angular 12: The module "@firebase/firestore" does not have an exported member named "type"

I am currently developing a project using Angular 12 and Firestore to store my data. Within my app module, I have imported the required modules in the following way (they were automatically added when I integrated Firebase into my project): import { init ...

A method for separating arrays within a string based solely on the commas between each one

I am working with a string containing an array of arrays that needs to be split into individual arrays. array = "[['<1>', 'likes'], ['<2>', 'reads'], ['<3>', \"doesn't ...

Guide to transforming a Javascript array into a JSON string

There is an array named values that contains the following data: var values = new Array(); values.push("english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav"); values.push("kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav"); ...

"Angular fails to retrieve any data from JSON API, returning a blank response

My ng-repeat function is not returning anything, and as a beginner in Angular, I am struggling to identify the error. Despite thorough error checking, I can't seem to figure out what's going wrong here. (function() { var app = angular.module( ...

Encountered a ZoneAwareError while trying to import the InfiniteScrollModule

Upon importing the InfiniteScrollModule from 'angular2-infinite-scroll' into my module, a ZoneAwareError is displayed https://i.sstatic.net/G2T94.png ...

I am attempting to retrieve JSON data from bitbns.com, however I am encountering an issue

Being new to javascript, I recently attempted to retrieve json data from bitbns but encountered the error - "(Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘’)." I scoured the internet in search of a solution, but unfortunately ...

Fetching data from a list separated by commas using Firebase database

Is there a way to store comma separated ids on a child node in Firebase and filter data similar to using the IN clause in SQL? If so, I would appreciate suggestions for possible solutions. ...

Field for user input featuring a button to remove the entry

I am attempting to add a close icon to a bootstrap 3 input field, positioned on the top right of the input. Here is what I have tried so far: https://jsfiddle.net/8konLjur/ However, there are two issues with this approach: The placement of the × ...

Using jQuery to retrieve values from clicked buttons

I'm trying to retrieve the values of a jQuery button upon form submission, but my current setup is not working. Specifically, I need to extract the value of data-url. Below is the code snippet I am using: $("#addAgency").submit(function(event) { ...

Blending a series of filter lists together

I am trying to combine the firstname and lastname as a single filter input. Currently, I have 4 filters that work fine individually. How can I create a single input for both first name and last name so that when a user types a name, it will search for ma ...

Generating JSON files using PHP

I have a simple setup with an input field and a submit button. My goal is to take the value entered into the input, convert it into JSON, and save that JSON data in a file on the server for later use. I am employing AJAX along with a small PHP script to ma ...

Creating a sleek animated analog clock using CSS and jQuery

I am facing a small issue with my CSS3/jQuery analog clock. Currently, the movement of the clock hands is a bit abrupt. I would like the animation to be smooth. I attempted using transition: all .1s, but it gets messy when the clock hands reach the top po ...