JavaScript String Object
This tutorial introduces the JavaScript String object. Strings are the native JavaScript data type used to hold text values; any JavaScript object can easily be converted to a string using the universal toString()
method.
Strings can even contain numbers: but numbers enclosed in quotes (single or double) cannot be used for mathematical operations before first being converted. The same applies for a quoted boolean of true or false.
What is a String?
A JavaScript string is a variable container designed for text, or any values directly or indirectly converted to String data type (text).
The single most common trait of strings is to be enclosed in single- or double-quotes. Both variables declared below are strings; they in fact are identical. (Single- and double-quotes are interchangeable in JavaScript.)
var carter1 = "I learn JavaScript";
var carter2 = 'I learn JavaScript';
Both variables are easily recognized as strings, thanks to their enclosure in quotes. Our next tutorial explains how to declare strings in JavaScript.
JavaScript String Properties
Properties are "attributes" attached to string-type values in JavaScript. In the case of strings, we have three properties at our disposal:
- The length property returns the number of characters a string contains.
- The constructor property points to the function used to create the string.
- The prototype property gives you access to the native String data type.
JavaScript String Methods
Our tutorials will cover the most common JavaScript string methods. Methods are special functions available to different types of objects; like other objects, JavaScript strings have numerous manipulation and conversion methods.
- The charAt() method returns the character at a given position index.
- The charCodeAt() method returns the Unicode encoding of a character.
- The concat() method joins together a string with other substrings.
- The fromCharCode() method converts a Unicode value to a character.
- The indexOf() method retrieves the first instance of a substring in a string.
- The lastIndexOf() method retrieves the last instance of a substring in a string.
- The slice() method returns a substring based on position index and length.
- The split() method creates an array from a string using a string delimiter.
- The substr() method returns a substring of relative length based on position index.
- The substring() method returns a substring based on a start and end position index.
- The toLowerCase() method returns a copy of a string converted to lowercase letters.
- The toUpperCase() method returns a copy of a string converted to uppercase letters.