Pattern Matching

[Total: 0    Average: 0/5]

RegExp is an object, but anything between 2 “/”‘s is a literally created object.

Body Code:

<script type=text/javascript>
 var url    = /(w+)://([w.|-]+)/(S*)/
 var text   = "Visit my home page at http://www.js-examples.com/nopath"
 var result = text.match(url)
 if (result != null) {
  var fullurl  = result[0]
  var protocol = result[1]
  var host     = result[2]
  var path     = result[3]
 }
document.writeln("<BR><BR><HR><div class=result>");
document.writeln("TEXT="+text+"<BR>result="+result+"<BR>")
document.writeln(" searched for "+url+"<BR>")
document.writeln(" fullurl="+fullurl+"<BR>")
document.writeln(" protocol="+protocol+"<BR>")
document.writeln(" host="+host+"<BR>")
document.writeln(" path="+path+"<BR>")

document.writeln("<BR><BR><HR>");
document.writeln("123,456,789.split(',')[1]="+"123,456,789".split(",")[1]+"<BR>");

document.writeln("<BR><BR><HR>");
document.writeln("'1,2,3, 4, 5, 6,7 ,   8,  9'.split(/s*,s*/)="+
                  "1,2,3, 4, 5, 6,7 ,   8,  9".split(/s*,s*/)+"<BR>");

document.writeln("<BR><BR><HR>");
var pattern = /java/i // case insensitive search
document.writeln("test for pattern in JavaScript="+pattern.test("JavaScript")+"<BR>");

document.writeln("<BR><BR><HR>");
var pattern2 = /Java/g
var text = "JavaScript is more fun than Java!"
var result
var i=0
while((result= pattern.exec(text)) != null) {
  document.writeln("Matched "+result[0]+" at position "+result.index+"<BR>")
  if (++i>10) break;  // it seems that both IE and NS don't work
}
</script>

Times Viewed: 1

Leave a Reply

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