JS String Reference and Code Samples

length

the built-in length property returns the length of a string

strLen = string.length;

script 1

let text1 = "an example string";
let length = text1.length;
document.getElementById('output1').innerHTML = length;



slice()

the slice method extracts part of a string and returns the extracted part in a new string. the end position is not included.

newStr = text.slice(startPosition, endPosition);

script 2

let text2 = "Apple, Banana, Kiwi";
let part2 = text2.slice(7, 13);
document.getElementById('output2').innerHTML = "output: " + part2;



substring()

substring is similar to slice, except that the start and end values less than 0 are treated as 0 in substring

let newStr = str.substring(startPosition, endPosition);

script 3

let string3 = "Apple, Banana, Kiwi";
let part3 = string3.substring(7, 13);
document.getElementById('output3').innerHTML = "output: " + part3;



split()

the split method splits a string into an array of substrings, then returns the new array and not the original string.
the strings can be split by " " blank space, "," commas, or "|" pipes.

const myArray = str.split(" ");

script 4

let str4 = "How are you doing today?"
const myArray = str4.split(" ");
let newSubStr = myArray[1]; document.getElementById('output4').innerHTML = "output: " + newSubStr;



replace()

the replace method replaces a specified value with another value in a string
the replace method will change only the first match. use replaceAll to replace all matches.

let newStr = str.replace("removeStr", "replaceStr");

script 5

let str5 = "Please visit Microsoft!";
let newStr5 = str5.replace("Microsoft", "W3Schools");
document.getElementById('output5').innerHTML = "output: " + newStr5;



trim()

the trim method can remove all the extra white space from a string

let newStr = oldStr.trim();

script 6

let scr6 = " *white space* Hello World! *white space* ";
let scr6a = scr6.trim();
document.getElementById('output6').innerHTML = "output: " + scr6a;



toUpperCase()

converts the entire string to upper case

let newStr = oldStr.toUpperCase();

Script 7

let str7 = "Hello World!";
let str7a = str7.toUpperCase();
document.getElementById('output7').innerHTML = "output: " + str7a;



charAt()

this method returns the character at a specified index in a string.

let char = str.charAt(indexPosition);

script 8

let str8 = "HELLO WORLD";
let char = str8.charAt(0);
document.getElementById('output8').innerHTML = 'output: ' + char;