How to use Regular Expression In Javascript

Regular expressions can also be used to validate JSON strings.

This regular expression checks if the given string conforms to the syntax of a JSON string by matching the basic structure and escaping rules of JSON strings. If the string passes the regex test, it returns true; otherwise, it returns false.

Example:

JavaScript
// Input string
let str = '{ "prop_1": "val_1", "prop_2": "val_2" }';
console.log("Input string is : " + str);

// Function to test string
function isJSON(str) {
    const jsonRegex = /^[\],:{}\s]*$/
        .test(str.replace(/\\["\\\/bfnrtu]/g, '@')
        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
        .replace(/(?:^|:|,)(?:\s*\[)+/g, ''));
    return jsonRegex;
}

// Function to display output
function gfg_Run() {
    console.log(isJSON(str));
}

// Function call
gfg_Run();

Output
Input string is : { "prop_1": "val_1", "prop_2": "val_2" }
true




Check if a string is a valid JSON string using JavaScript

We will be given a string and we need to validate whether the given string is a valid JSON string or not. JSON string is the same as a javaScript object and it must follow the syntax of that object. If the syntax is correct then we have to return true or we have to return false.

Methods to Check if a String is Valid JSON String:

Table of Content

  • Method 1: Using JSON.parse() method
  • Method 2: Using JSON.stringify() method
  • Method 3: Using Lodash _.isJSON() Method
  • Method 4: Using Regular Expression

Similar Reads

Method 1: Using JSON.parse() method

The  JSON.parse() method in JavaScript is used to parse a JSON string which is written in a JSON format and returns a JavaScript object....

Method 2: Using JSON.stringify() method

The JSON.stringify() method in Javascript is used to create a JSON string out of it....

Method 3: Using Lodash _.isJSON() Method

In Lodash _.isJSON() Method approach, we are using Lodash _.isJSON() method that returns the boolean value that is true if the passes value is a JSON string else it returns false....

Method 4: Using Regular Expression

Regular expressions can also be used to validate JSON strings....