JavaScript String search() With a Regular Expression

Here is a very simple example of using a regular expression in the Search() method of a string. The string is Visit W3Schools! You can get the start position of a string within a string. It is from When you click the Try It button you should see the number 6 appear, if the code is working. When you click the Try it button below there is a click event attached to the button that calls JavaScript code. The code is shown below.

Search a string for “w3Schools”, and display the position of the match:

Below is the HTML used in this post.

<p>Search a string for "w3Schools", and display the position of the match:</p>
<button onclick="pwSearchRegExpFunction()">Try it</button>
<p id="demoSearchRegExp"></p>

Below is the JavaScript used in this post.

function pwSearchRegExpFunction() {
    var str = "Visit W3Schools!"; 
    var n =;
    document.getElementById("demoSearchRegExp").innerHTML = n;

This is a WordPress site and I will use the Enqueue to add this function to the footer of all of the pages in the site. My file name that contains this function is called pw_Search_RegExp_Function.js.

Series Navigation<< Regular Expressions Introduction

Leave a comment

Your email address will not be published. Required fields are marked *