How to Use String Regex in JavaScript?

Estimated read time 2 min read

In JavaScript, you can use regular expressions (regex) to perform pattern matching on strings. A regular expression is a sequence of characters that defines a search pattern. These patterns can be used to validate user input, search for strings within a larger string, and perform other string manipulations.

Here’s an example of using a regex pattern in JavaScript:

const string = "Hello, World!";
const pattern = /Hello/;

const result = pattern.test(string);

console.log(result); // true

In this example, the pattern is a regular expression that matches the string “Hello”. The test method of the pattern object is then used to search for a match within the string “Hello, World!”. The result of this test is a boolean value indicating whether the pattern was found in the string.

You can also use the exec method to extract the matched text from the string:

const string = "Hello, World!";
const pattern = /Hello/;

const result = pattern.exec(string);

console.log(result[0]); // Hello

In this example, the exec method returns an array with the matched text as the first element, and any capture groups as additional elements.

Here are some common regex patterns and their uses:

  • /\d/: matches a single digit (0-9)
  • /\w/: matches a word character (letters, digits, and underscores)
  • /\s/: matches a whitespace character (space, tab, line break)
  • /^hello/: matches the string “hello” at the beginning of a line
  • /world$/: matches the string “world” at the end of a line

This is just a brief introduction to using regex in JavaScript. Regular expressions can be a powerful tool for string manipulation, but they can also be complex and difficult to read if not used carefully. I recommend consulting the documentation or a tutorial for more information.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply