| Refresh | Home EGTry.com

commonly used string properties and methods


commentsJavascript sourceExecution result in your current browser
initialize a string
var s=new String("Hello World");
var line="Hello World";

length property
document.write(line.length);

charAt
document.write("first char: "+line.charAt(0));
document.write("<br/>last char: "+line.charAt(line.length-1));

indexOf and lastIndexOf - find a substring position
  line="username@mail.egtry.com";
  document.write("first occurrence is: "+line.indexOf(".")+"<br/>");
  document.write("last occurrence is: "+line.indexOf(".")+"<br/>");
  document.write("not found index: "+line.indexOf("##")+"<br/>");

substr (length) substring (index)
  line="214-123-4567";
  document.write("area code is: "+line.substring(0,3)+"<br/>");
  document.write("phone number: "+line.substr(4)+"<br/>");

toLowerCase and toUpperCase
  line="Super 8";
  document.write("all uppercase: "+line.toUpperCase()+"<br/>");
  document.write("all lowercase: "+line.toLowerCase()+"<br/>");

capitalize
  line="helpDESK";
  document.write("capitalized word: "
   +line.substr(0,1).toUpperCase()+line.substr(1).toLowerCase());