Javascript String

Javascript String length

Javascript String Object, which is one of the native object , is a wrapper class for all strings. The String object has a few properties and methods, most of which it inherits from Object.

String Length

The String.length property returns an integer value that is the result of total number of characters in the string.

Syantax:

string.length;

E.g.

var str = "This is a string"; var length = str.length; alert( "Length is "+length);

Above script will alert "Length is 16"

trim() method

Javascript String trim() method

Javascript string trim() method returns a new string with all leading and trailing whitespaces removed from the original string. The original string is not changed.

Syntax:

string.trim();

E.g.

var str = " This is a string "; document.write("$" + str + "$" + "<br>"); document.write("$" + str.trim() + "$");

Output:

Javascript string trim method

In the above output, you can see the leading and trailing whitespaces removed from the original string

String trimLeft()

Javascript String.trimLeft() method returns a new string with all leading whitespaces removed. The original string is not changed.

Syntax:

string.trimLeft();

E.g.

var str = " This is a string "; document.write("$" + str + "$" + "<br>"); document.write("$" + str.trimLeft() + "$");

Output:

javascript string trimleft

In the above output, you can see the leading whitespaces (left side spaces) removed from the original string

String trimRight()

Javascript String.trimRight() method returns a new string with all trailing whitespaces removed. The original string is not changed.

Syntax:

string.trimRight();

E.g.

var str = " This is a string "; document.write("$" + str + "$" + "<br>"); document.write("$" + str.trimRight() + "$");

Output:

javascript trim right

In the above output, you can see the trailing whitespaces (right side spaces) removed from the original string

String toLowerCase()

Javascript String toLowerCase

Javascript String toLowerCase() method returns the value of the string with all characters converted to lowercase. It will not affect the value of the original string itself.

Syntax:

string.toLowerCase()

E.g.

var str = " This is a string "; document.write(str.toLowerCase());

When you run the above script, the output is "this is a string".

String toUpperCase()

Javascript String toUpperCase() method returns the value of the string with all characters converted to uppercase. It will not affect the value of the original string itself.

Syntax:

string.toUpperCase()

E.g.

var str = " This is a string "; document.write(str.toUpperCase());

When you run the above script, the output is "THIS IS A STRING".