JavaScript tutorial-global search and case-insensitive


Regular Expression

Global search and case-insensitive

In general, Regular Expression object matches only the first string pattern. This means that when the string pattern is matched at the first time in another string then the searching process will stop.

For example, we have a string "JavaScript-HTML-CSS". We want to replace the minus signs(-) with commas. Our string and string pattern should be:

var st="JavaScript-HTML-CSS";

var stpat=/-/;

To replace the minus signs with commas, the replace() method is used:

var stnew=st.replace(stpat,",");

Now let see the full code:

<html>
<head>
<title>Regular Expression-a simple string pattern</title>

<script language="JavaScript" type="text/javascript">

var st="JavaScript-HTML-CSS";
var stpat=/-/;
var stnew=st.replace(stpat,",");
document.write(stnew+"<br>");

</script>

</head>
<body>
</body>
</html>

By executing this code on a browser, you will get:

JavaScript,HTML-CSS

It is not want we really want. We want all the minus signs are replaced by commas. To solve this problem, you need to use the g character with the string pattern:

var stpat=/-/g;

Therefore, the code above should be modified to:

<html>
<head>
<title>Regular Expression-a simple string pattern</title>

<script>

var st="JavaScript-HTML-CSS";
var stpat=/-/g;
var stnew=st.replace(stpat,",");
document.write(stnew+"<br>");

</script>

</head>
<body>
</body>
</html>

The Regular Expression object is case-sensitive. The lower case  and upper case letters are treated differently. If you want a pattern to be matched in case-insensitive manner, you need to use the i character with your string pattern:

var stpat=/-/gi;




Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.