String:
- One dimensional character array.
- String is an object.
- String object providing functionality to perform string operations.
Syntax: var name = “amar” ;
Program to define a string and display:
<html> <body> <script> var name = “amar” ; document.write(“Hello ” + name); </script> </body> </html> |
Find the length of String: ‘length’ property is used to find the length of the string.
<html> <body> <script> var name = “amar” ; document.write(“Length is : ” + name.length); </script> </body> </html> |
JavaScript providing pre-defined function to process String objects:
Function | Description |
charAt() | returns the character of specified index |
concat() | merge 2 strings |
indexOf() | it returns index value of specified character. |
substr() | it is used to fetch sub string from the given string |
toLowerCase() | converts upper case characters into lower case |
to UpperCase() | converts lower case characters into upper case |
toString() | Converts any object into String. |
valueOf() | provides primitive value of String object. |
split() | split string into substring array. |
trim() | it trims white spaces from the left and right side of the string. |
Display first and last character of specified string:
<html> <body> <script> var name = “amar” ; document.write(“String : ” + name + “<br/>”); document.write(“First char: ” + name.charAt(0) + “<br/>”); document.write(“Last char: ” + name.charAt(name.length-1)); </script> </body> </html> |
Display all characters in the String one by one:
<html> <body> <script> var name = “amar” ; for(var i=0 ; i<= name.length-1 ; i++) { document.write(name.charAt(i) + “<br/>”); } </script> </body> </html> |