Strings

A JavaScript string stores a series of letters, numbers, and punctuation characters. For example, a string could contain the word "Ollie". To define a string's value, wrap the desired characters in double or single quotes. The quotes are not part of the stored value. String indices are zero-based: The first character is position 0, the second is 1, etc.

var robot = 'Ollie';

var report = "Wow! Ollie just did a 720 in mid-air!";


String Properties

constructor returns the string's constructor function

length returns the length of a string

prototype allows you to add properties and methods to an object


String Methods

charAt() returns the character at the specified index (position)

charCodeAt() returns the Unicode of the character at the specified index

concat() joins two or more strings, and returns a new joined strings. You can also use the + operator to do this.

Example: combine strings before speaking:

async function startProgram() {

var start = "This is a ";

var end = "complete sentence.";

speak(start + end);

await delay(2.0);

}

endsWith() checks whether a string ends with specified string/characters

fromCharCode() converts Unicode values to characters

includes() checks whether a string contains the specified string/characters

indexOf() returns the position of the first found occurrence of a specified value in a string

lastIndexOf() returns the position of the last found occurrence of a specified value in a string

localeCompare() compares two strings in the current locale

match() searches a string for a match against a regular expression, and returns the matches

repeat() returns a new string with a specified number of copies of an existing string

replace() searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced

search() searches a string for a specified value, or regular expression, and returns the position of the match

slice() extracts a part of a string and returns a new string

split() splits a string into an array of substrings

startsWith() checks whether a string begins with specified characters

substr() extracts the characters from a string, beginning at a specified start position, and through the specified number of characters

substring() extracts the characters from a string, between two specified indices

toLocaleLowerCase() converts a string to lowercase letters, according to the host's locale

toLocaleUpperCase() converts a string to uppercase letters, according to the host's locale

toLowerCase() converts a string to lowercase letters

toString() returns the value of a String object

toUpperCase() converts a string to uppercase letters

trim() removes whitespace from both ends of a string

valueOf() returns the primitive value of a String object