Javascript String

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.

Syntax

string.length;

example

	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 returns a new string with all leading and trailing whitespaces removed from the original string. The original string is not changed.

Syntax

string.trim();

example

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

output

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();

example

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

output

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();

example

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

Output:

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

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()

example

	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()

example

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

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