js regex match start and end of string

JS Regex: Match Start and End of String

Regular expressions, or regex, are a powerful and flexible tool for searching, matching, and manipulating text. They can be used in many programming languages, including JavaScript.

If you want to match the start or end of a string in JavaScript using regex, there are a few different ways to do it.

Match Start of String

To match the start of a string using regex in JavaScript, you can use the caret (^) character. This character is called an anchor and represents the start of the string:


let str = "Hello World";
let regex = /^Hello/;

if (regex.test(str)) {
  console.log("Match found at start of string");
}

In this example, we're testing whether the string "Hello World" starts with "Hello" using the regex /^Hello/. The test() method returns true because the regex matches the start of the string.

Match End of String

To match the end of a string using regex in JavaScript, you can use the dollar sign ($) character. This character is also an anchor and represents the end of the string:


let str = "Hello World";
let regex = /World$/;

if (regex.test(str)) {
  console.log("Match found at end of string");
}

In this example, we're testing whether the string "Hello World" ends with "World" using the regex /World$/. The test() method returns true because the regex matches the end of the string.

Match Start and End of String

You can also match both the start and end of a string using regex in JavaScript. To do this, you can combine the caret (^) and dollar sign ($) characters:


let str = "Hello World";
let regex = /^Hello.*World$/;

if (regex.test(str)) {
  console.log("Match found at start and end of string");
}

In this example, we're testing whether the string "Hello World" starts with "Hello" and ends with "World" using the regex /^Hello.*World$/. The test() method returns true because the regex matches the start and end of the string.

Overall, using regex to match the start and end of a string in JavaScript can be a useful technique for a variety of text processing tasks.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe