JavaScript Regular expressions Using RegExp With Strings

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

The String object has the following methods that accept regular expressions as arguments.

  • "string".match(...
  • "string".replace(...
  • "string".split(...
  • "string".search(...

Match with RegExp

console.log("string".match(/[i-n]+/));
console.log("string".match(/(r)[i-n]+/));

Expected output

Array ["in"]
Array ["rin", "r"]

Replace with RegExp

console.log("string".replace(/[i-n]+/, "foo"));

Expected output

strfoog

Split with RegExp

console.log("stringstring".split(/[i-n]+/));

Expected output

Array ["str", "gstr", "g"]

Search with RegExp

.search() returns the index at which a match is found or -1.

console.log("string".search(/[i-n]+/));
console.log("string".search(/[o-q]+/));

Expected output

3
-1



Got any JavaScript Question?