We can read properties like length and toUpperCase from string values. But if you try to add a new property, it doesn’t stick.
let kim = “Kim”;
kim.age = 88;
console.log(kim.age); // → undefined
Values of type string, number, and Boolean are not objects, and though the language doesn’t complain if you try to set new properties on them, it doesn’t actually store those properties. As mentioned earlier, such values are immutable and cannot be changed.
But these types do have built-in properties. Every string value has a number of methods. Some very useful ones are slice and indexOf, which resemble the array methods of the same name.
// → nut
// → 5
One difference is that a string’s indexOf can search for a string containing more than one character, whereas the corresponding array method looks only for a single element.
console.log(“one two three”.indexOf(“ee”));
// → 11
The trim method removes whitespace (spaces, newlines, tabs, and similar characters) from the start and end of a string.
console.log(” okay \n “.trim());
// → okay
The zeroPad function from the previous chapter also exists as a method. It is called padStart and takes the desired length and padding character as arguments.
// → 006
You can split a string on every occurrence of another string with split and join it again with join.
let sentence = “Secretarybirds specialize in stomping”;
let words = sentence.split(” “);
// → [“Secretarybirds”, “specialize”, “in”, “stomping”] console.log(words.join(“. “));
// → Secretarybirds. specialize. in. stomping
A string can be repeated with the repeat method, which creates a new string containing multiple copies of the original string, glued together.
// → LALALA
We have already seen the string type’s length property. Accessing the individual characters in a string looks like accessing array elements (with a caveat that we’ll discuss in “Strings and Character Codes” on page 92).
let string = “abc”;
// → 3
// → b
No Starch Press; 3rd edition.