Javascript String Object

A JavaScript String object represents a sequence of characters.

How to create a Javascript string object:

1. By using string literals.
2. By using String() constructor.

By using string literals:

When we create a string literal browser automatically converts it to a String object.

Syntax:

var string1 = “value”;

Example:

<!DOCTYPE html>
<html>
<body>
<script>
var string1="String example by string literal.";
document.write(string1);
</script>
</body>
</html>

Try it:

JS Bin on jsbin.com

By using String() constructor:

We can create a JavaScript String object by using the String() constructor.

Syntax:

var string1 = new String(value);

Example:

<!DOCTYPE html>
<html>
<body>
<script>
var string1=new String("String example by String constructor.");
document.write(string1);
</script>
</body>
</html>

Try it:

JS Bin on jsbin.com

JavaScript String Object Properties:

Property Description
constructor It returns a reference to the String function that created the object.
length It returns the length of the string.
prototype It allows us to add properties and methods to an object.

 

JavaScript String Object Methods:

Method Description
charAt() It returns the character at the specified index.
charCodeAt() It returns a number indicating the Unicode value of the character at the given index.
concat() It combines the text of two strings and returns a new string.
indexOf() It returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
lastIndexOf() It returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
match() It is used to match a regular expression against a string.
replace() It is used to find a match between a regular expression and a string and to replace the matched substring with a new substring.
search() It executes the search for a match between a regular expression and a specified string.
slice() It extracts a section of a string and returns a new string.
substr() It returns the characters in a string beginning at the specified location through the specified number of characters.
substring() It returns the characters in a string between two indexes into the string.
toLowerCase() It returns the calling string value converted to lowercase.
toLocaleLowerCase() The characters within a string are converted to lowercase while respecting the current locale.
toUpperCase() It returns the calling string value converted to uppercase.
toLocaleUpperCase() The characters within a string are converted to upper case while respecting the current locale.
toString() It returns a string representing the specified object.
valueOf() It returns the primitive value of the specified object.