revision:
You can use single or double quotes and you can use quotes inside a string, as long as they don't match the quotes surrounding the string.
With JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
REMINDER: JavaScript counts positions from zero. 0 is the first position in a string, 1 is the second, 2 is the third ...
For multiline string, instead of using the + operator with a new line ecape sequence (\n), backticks(` `) can be used.
longhand
const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t' + 'adipisicing elit, sed do eiusmod tempor incididunt\n\t' + 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t' + 'veniam, quis nostrud exercitation ullamco laboris\n\t' + 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t' + 'irure dolor in reprehenderit in voluptate velit esse.\n\t'
shorthand
const lorem = `Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse.`
You can embed a variable into a string by wrapping the string inside backticks and using ${}.
trick
const age = 41; const sentence = `I'm ${age} years old`; // result: I'm 41 years old let eggCount = 20; console.log(`On easter we decorted ${eggCount}` easter eggs); let a = 5; b = 10; console.log(`Sum of ${a} and ${b} is ${a + b}`);
There are multiple ways to calculate occurrences of a char in a string. The simplest and shortest is this one.
Example - code
const countOccurence = (str, char) => (str.split(char).length - 1); // example: countOccurence('mississippi','i'); //4
const countOccurrences = (str, char) => [...str].reduce((a, v) => (v === char ? a + 1 : a), 0);
const countOccurrences = (str, char) => str.split('').filter(item => item === char).length;
When a temporary unique id is needed, this trick can be used to generate a random string on the go.
Example - code
const randomString = () => Math.random().toString(36).slice(2); console.log(randomString()); // could be anything!!!
const randomID = Math.random().toString(36).substring(2)
const generateString = (length, chars) => Array(length).fill('').map((v) => chars[Math.floor(Math.random() * chars.length)]).join('');
From the end, in the middle, in the beginning
Example - code
// from the end const truncateString = (string, length) => { return string.length < length ? string : `${string.slice(0, length - 3)}...`;}; console.log(truncateString('Hi, I should be truncated because I am too loooong!', 36),); // Hi, I should be truncated because...
// in the middle const truncateStringMiddle = (string, length, start, end) => { return `${string.slice(0, start)}...${string.slice(string.length - end)}`;}; console.log(truncateStringMiddle( 'A long story goes here but then eventually ends!', // string 25, // total size needed 13, // chars to keep from start 17, // chars to keep from end ), ); // A long story ... eventually ends!
const truncate = (str, max, suffix) => str.length < max ? str : `${str.substr(0, str.substr(0, max - suffix.length).lastIndexOf(' '))}${suffix}`; // Example truncate('This is a long message', 20, '...'); // 'This is a long...'
There are a couple different ways to reverse a string. The most simple ones are using the split(), reverse(), and join() methods.
Example - code
const reverse = str => str.split('').reverse().join(''); //example reverse('hello world'); // 'dlrow olleh'
const reverse = str => str.split('').reduce((rev, char)=> `${char}${rev}`, ''); //example reverse('hello world'); // 'dlrow olleh'
const reverse = str => (str === '') ? '' : `${reverse(str.substr(1))}${str.charAt(0)}`; //example reverse('hello world'); // 'dlrow olleh'
\' — Single quote: inserts a single quote in a string.
\" — Double quote: inserts a double quote in a string.
\\ — Backslash: inserts a backslash in a string.
\b — Backspace.
\f — Form feed.
\n — New line.
\r — Carriage return.
\t — Horizontal tabulator.
\v — Vertical tabulator.
Syntax: string.charAt(index)
Parameters:
index: optional. The index (position) of the character. Default = 0.
Examples
<div class="spec"> <a id="method20"></a><br> <a id="method20a"></a><br> <a id="method20b"></a> </div> <script> var str = "HELLO WORLD"; document.getElementById("method20").innerHTML = str + " : " + "index[0]: " + str.charAt(0) + " : " +"index[6]: " + str.charAt(6); let text_1 = "HELLO WORLD"; let letter_1 = text_1.charAt(6); document.getElementById("method20a").innerHTML = "position six :" + letter_1; let letter_2 = text_1.charAt(12); document.getElementById("method20b").innerHTML = "position twelve :" + letter_2; </script>
Syntax: string.charCodeAt(index)
Parameters:
index: optional. A number. The index (position) of the character. Default = 0.
The charCodeAt() method returns the Unicode of the character at a specified index (position) in a string. The index of the first character is 0, the second is 1, .... The index of the last character is string length - 1.
Examples
<div class="spec"> <a id="method21"></a><br> <a id="method21a"></a><br> <a id="method21b"></a><br> </div> <script> var str = "HELLO PEOPLE"; document.getElementById("method21").innerHTML = str + " : " + "index[0]: " + str.charCodeAt(0) + " : "+"index[6]: " + str.charCodeAt(6); let text_2 = "HELLO WORLD"; let code_1 = text_2.charCodeAt(text_2.length-1); document.getElementById("method21a").innerHTML = text_2 + " : " + "last but one position:" +code_1; let code_2 = text_2.charCodeAt(15); document.getElementById("method21b").innerHTML = text_2 + " : " + "position 15: " +code_2; </script>
Syntax: string.codePointAt(index)
Parameters:
index: optional. The index (position) in a the string. Default value = 0.
charCodeAt() is UTF-16, codePointAt() is Unicode. charCodeAt() returns a number between 0 and 65535. Both methods return an integer representing the UTF-16 code of a character, but only codePointAt() can return the full value of a Unicode value greather 0xFFFF (65535)..
Examples
<div class="spec"> <a id="methd1"></a><br> <a id="methd1a"></a><br> <a id="methd1b"></a><br> </div> <script> let text_3 = "HELLO WORLD"; let code_3 = text_3.codePointAt(0); document.getElementById("methd1").innerHTML = "codePoint at index 3 : " + code_3; let code_4 = text_3.codePointAt(1); document.getElementById("methd1a").innerHTML = "codePoint at index 1 : " + code_4; let code_5 = text_3.codePointAt(15); document.getElementById("methd1b").innerHTML = "codePoint at index 15 : " +code_5; </script>
Syntax: string.concat(string1, string2, ..., stringX)
Parameters:
string1, string2, ..., stringX: required. The strings to be joined.
The concat() method can be used instead of the plus (+) operator. The concat() method does not change the existing strings and it returns a new string.
Examples
<div class="spec"> <p>Click the button to join two strings into one new string.</p> <button onclick="myFunctionA()">Try it</button><br> <a id="method21A"></a><br> <a id="method21B"></a><br> <a id="method21C"></a> </div> <script> function myFunctionA() { var str1 = "Hello "; var str2 = "world!"; var res = str1.concat(str2); document.getElementById("method21A").innerHTML = str1 + " + " + str2 + "-> concat: " + res; } let text1a = "Hello"; let text2a = "world!"; let result_ab = text1a.concat(" ", text2a); document.getElementById("method21B").innerHTML = text1a + " + " + text2a + "=" + result_ab; let text1c = "Hello"; let text2c = "world!"; let text3c = "Have a nice day!"; let result_ccc = text1c.concat(" ", text2c, " ", text3c); document.getElementById("method21C").innerHTML = text1c + " +" + text2c + " + " + text3c + "->" + result_ccc; </script>
Syntax: string.constructor
The constructor property returns the function that created the String prototype. For JavaScript strings the constructor returns: function String() { [native code] }
Examples
<div class="spec"> <a id="property2"></a><br> <a id="property2a"></a> </div> <script> var str = "Hello World!"; document.getElementById("property2").innerHTML = str + " : " + str.constructor; let message = "Hello World!"; let textd = message.constructor; document.getElementById("property2a").innerHTML = textd; </script>
Syntax: string.endsWith(searchvalue, length)
Parameters:
searchvalue: required. The string to search for.;
length: optional. The length of the string to search. Default value is the length of the string.
The endsWith() method is case sensitive.
Examples
<div class="spec"> <a id="method221C"></a><br> <a id="method221D"></a><br> <a id="method221E"></a> </div> <script> let text_e = "Hello world"; let result_e = text_e.endsWith("world"); document.getElementById("method221C").innerHTML = "ends with 'world' : " + result_e; let result_ee = text_e.endsWith("World"); document.getElementById("method221D").innerHTML = "ends with 'World' : " +result_ee; let str_e = "Hello world, welcome to the universe."; document.getElementById("method221E").innerHTML = "ends with 'world' in position 11: " + str_e.endsWith("world", 11); </script>
Syntax: String.fromCharCode(n1, n2, ..., nX)
Parameters:
n1, n2, ..., nX: required. One or more Unicode values to be converted.
The fromCharCode() method converts unicode values into characters. It is a static method of the String object. The syntax is always String.fromCharCode().
Examples
<div class="spec"> <p>Click the button to display the character of the specified unicode number.</p> <button onclick="myFunctionB()">Tty it</button><br> <a id="method21BC"></a> <br> <a id="method21BD"></a> </div> <script> function myFunctionB() { var res = String.fromCharCode(65); document.getElementById("method21BC").innerHTML = "Charcode 65: " + res; } let text_f = String.fromCharCode(72, 69, 76, 76, 79); document.getElementById("method21BD").innerHTML = "text from charcode series : " + text_f; </script>
Syntax: string.includes(searchvalue, start)
Parameters:
searchhvalue: required. The string to search for.;
start: optional. The position to start from. Default value is 0.
The includes() method is case sensitive.
Examples
<div class="grid"> <div class="spec"> <a id="method_1"></a><br> <a id="method_1a"></a> </div> <script> let text_g = "Hello world, welcome to the universe."; let result_g = text_g.includes("world"); document.getElementById("method_1").innerHTML = "includes 'world'? : " + result_g; let result_gg = text_g.includes("world", 12); document.getElementById("method_1a").innerHTML = "includes 'world at position 12'? : " + result_gg; </script>
multiple string checks
longhand
const isVowel = (letter) => { if ( letter === "a" || letter === "e" || letter === "i" || letter === "o" || letter === "u" ) { return true; } return false; };
shorthand
const isVowel = (letter) => ["a", "e", "i", "o", "u"].includes(letter);
Syntax: string.indexOf(searchvalue, start)
Parameters:
searchvalue: required. The string to search for.
start: optional. The position to start from (default is 0). ;
The indexOf() method returns -1 if the value is not found. It is case sensitive.
Examples
<div class="spec"> <a id="method1"></a><br> <a id="method1a"></a><br> <a id="method1b"></a><br> <a id="method1c"></a><br> <a id="method1d"></a><br> <a id="method1e"></a><br> </div> <script> var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate"); document.getElementById("method1").innerHTML = str + " : " + pos + "th position"; let text_i = "Hello world, welcome to the universe."; let result_i = text_i.indexOf("welcome"); document.getElementById("method1a").innerHTML = "index of 'welcome' :" + result_i; let result_ii = text_i.indexOf("Welcome"); document.getElementById("method1b").innerHTML = "index of 'Welcome' :" + result_ii; document.getElementById("method1c").innerHTML = "index of 'e' :" + text_i.indexOf("e"); document.getElementById("method1d").innerHTML = "index of 'e' to start from position 5 :" + text_i.indexOf("e", 5); document.getElementById("method1e").innerHTML = "index of 'a' to start from position 5 :" + text_i.indexOf("a", 5); </script>
Syntax: string.lastIndexOf(searchvalue, start)
Parameters:
searchvalue: required. The string to search for.
start: optional. The position where to start. Default value is string length.
The lastIndexOf() method searches the string from the end to the beginning. It returns the index from the beginning (position 0) and returns -1 if the value is not found. The method is case sensitive.
Examples
<div class="spec"> <a id="method2"></a><br> <a id="method2a"></a><br> <a id="method2b"></a><br> <a id="method2c"></a><br> </div> <script> var str = "Please locate where 'locate' occurs!"; var pos = str.lastIndexOf("locate"); document.getElementById("method2").innerHTML = str + " : " + pos + "th position"; let text_j = "Hello planet earth, you are a great planet."; let result_j = text_j.lastIndexOf("planet"); document.getElementById("method2a").innerHTML = "last index of 'planet' :" + result_j; let result_jj = text_j.lastIndexOf("Planet"); document.getElementById("method2b").innerHTML = "last index of 'Planet' :" + result_jj; let result_jjj = text_j.lastIndexOf("planet", 20); document.getElementById("method2c").innerHTML = "last index of 'planet' starting from position 20 :" + result_jjj; </script>
Syntax: string.length
Parameters: none
The length property of an empty string is 0.
Examples
<div class="spec"> <a id="property1"></a><br> <a id="property1a"></a> </div> <script> var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var sln = txt.length; document.getElementById("property1").innerHTML = txt + " : " + sln; let text_k = "Hello World!"; let length = text_k.length; document.getElementById("property1a").innerHTML = text_k + length; </script>
Syntax: string.localeCompare(compareString)
Parameters:
compareString : required. The string to compare with.
The localeCompare() method returns sort order -1, 1, or 0 (for before, after, or equal). The current locale is based on the language settings of the browser.
<>examples>
Compare "ab" with "cd":
Compare "cd" with "ab":
Compare "ab" with "ab":
<div class="spec"> <ul> <li>-1 if sorted before</li> <li>1 if sorted after</li> <li>0 if equal</li> </ul> <p>Compare "ab" with "cd":</p> <p id="comp"></p> <p>Compare "cd" with "ab":</p> <p id="comp1"></p> <p>Compare "ab" with "ab":</p> <p id="comp2"></p><br> </div> <script> let text1 = "ab"; let text2 = "cd"; let result_k = text1.localeCompare(text2); document.getElementById("comp").innerHTML = result_k; let text1_1 = "cd"; let text2_1 = "ab"; let result_kk = text1_1.localeCompare(text2_1); document.getElementById("comp1").innerHTML = result_kk; let text1_2 = "ab"; let text2_2 = "ab"; let result_kkk = text1_2.localeCompare(text2_2); document.getElementById("comp2").innerHTML = result_kkk; </script>
Syntax: string.match(match)
Parameters:
match: required. The search value. A regular expression (or a string) that will be converted to a regular expression.
The match() method searches a string for a match against a regular expression, and returns the matches, as an array object. The match() method returns null if no match is found.
Examples
Click the button to perfom a global search for the letters "ain" in a string, and display the matches.
<div class="spec"> <p>Click the button to perfom a global search for the letters "ain" in a string, and display the matches.</p> <button onclick="myFunctionC()">Try it</button><br> <a id="match1"></a><br> <a id="match2"></a><br> <a id="match3"></a><br> <a id="match4"></a><br> <a id="match5"></a><br> </div> <script> function myFunctionC() { var str = "The rain in SPAIN stays mainly in the plain"; var res_a = str.match(/ain/g); document.getElementById("match1").innerHTML = str + ". : " + "<br>" + "match: ->" + res_a; } let text_l = "The rain in SPAIN stays mainly in the plain"; let result_l = text_l.match("ain"); document.getElementById("match2").innerHTML = "ain : " + result_l; let result_ll = text_l.match(/ain/); document.getElementById("match3").innerHTML = "/ain/ : " + result_ll; let result_lll = text_l.match(/ain/g); document.getElementById("match4").innerHTML = "/ain/g : " + result_lll; let result_llll = text_l.match(/ain/gi); document.getElementById("match5").innerHTML = "/ain/gi : " + result_llll; </script>
Syntax: object.prototype.name = value
Parameters:
match:
The prototype is a property available with all JavaScript objects.
You are not advised to change the prototype of an object that you do not control. You should not change the prototype of built in JavaScript datatypes like: Numbers, Strings, Arrays, Dates, Booleans, Function, Objects. Only change the prototype of your own objects.
Examples
<div class="spec"> <a id="property3"></a><br> <a id="property3a"></a> </div> <script> function employee(name, jobtitle, born) { this.name = name; this.jobtitle = jobtitle; this.born = born; } employee.prototype.salary = 2000; var fred = new employee("Fred Flintstone", "Caveman", 1970); document.getElementById("property3").innerHTML = "prototype.salary: " + fred.salary; function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.eyeColor = eye; } const myFather = new Person("John", "Doe", "blue"); const myMother = new Person("Sally", "Rally", "green"); Person.prototype.nationality = "English"; document.getElementById("property3a").innerHTML = "My father is " + myFather.nationality + "<br>" + "My mother is " + myMother.nationality; </script>
Syntax: string.repeat(count)
Parameters:
count : required. The number of copies.
The repeat() method returns a new string and does not change the original string.
Examples
<div class="spec"> <p id="repeat1"></p><br> <p id="repeat2"></p><br> </div> <script> let text_m = "Hello world!"; let result_m = text_m.repeat(2); document.getElementById("repeat1").innerHTML = "repeat twice : " + result_m; let result_mm = text_m.repeat(4); document.getElementById("repeat2").innerHTML = "repeat four times : " +result_mm; </script>
The repeat() method constructs and returns a new string, which contains the specified number of copies of the string on which it was called, concatenated together.
longhand
let str = ''; for(let i = 0; i < 5; i ++) { str += 'Hello '; } console.log(str); // Hello Hello Hello Hello Hello function repeatStringNumTimes(string, times) { if(times < 0) return ""; if(times === 1) return string; else return string + repeatStringNumTimes(string, times - 1); } repeatStringNumTimes("abc", 3);
shorthand
'Hello '.repeat(5); function repeatStringNumTimes(string, times) { if (times > 0) return string.repeat(times); else return ""; } repeatStringNumTimes("abc", 3);
Syntax: string.replace(searchValue, newValue)
Parameters:
searchValue: required. The value, or regular expression, to search for.;
newValue: required. The new value (to replace with).
The replace() method does not change the string it is called on. It returns a new string. By default, the replace() method replaces only the first match, and the replace() method is case sensitive. To replace case insensitive, use a regular expression with an /i flag (insensitive)
Examples
Replace "Google" with "my website" in the paragraph:
Replace "Microsoft" with "my website" in the paragraph:
Please visit Microsoft and Microsoft !!Replace "Microsoft" with "my website" in the paragraph:
Please visit Microsoft !!Replace "Microsoft" with "my website" in the paragraph:
Please visit Microsoft and Microsoft !!<div class="spec"> <p style="margin-left: 2vw;">Replace "Google" with "my website" in the paragraph:</p> <button style="margin-left: 3vw;" onclick="myFunction()">Try it</button><br> <a id="replace1">Please visit Google !!</a><br> <a id="replace2">Please visit Google !!</a><br><br> <a id="replace3">Visit Microsoft!!</a><br> <a id="replace4">Visit Microsoft !!</a><br><br> <a id="replace5">Mr Blue has a blue house and a blue car.</a><br> <a id="replace6"></a><br> <a id="replace7"></a><br> <a id="replace8"></a><br> <p>Replace "Microsoft" with "my website" in the paragraph:</p> <button onclick="myFunction2()">try it</button> <a id="method13">Please visit Microsoft and Microsoft !!</a> <p>Replace "Microsoft" with "my website" in the paragraph:</p> <button onclick="myFunction3()">Try it</button> <a id="method14">Please visit Microsoft !!</a> <p>Replace "Microsoft" with "my website" in the paragraph:</p> <button onclick="myFunction4()">Try it</button> <a id="method15">Please visit Microsoft and Microsoft !!</a> </div> <script> function myFunction(){ var str = document.getElementById('replace1').innerHTML; var txt = str.replace("Google", "my website"); document.getElementById("replace2").innerHTML = txt; } let text_n = document.getElementById("replace3").innerHTML; document.getElementById("replace4").innerHTML = text_n.replace("Microsoft", "W3Schools"); let str_rep = document.getElementById("replace5").innerHTML; let res_rep = str_rep.replace(/blue/g, "red"); document.getElementById("replace6").innerHTML = res_rep; let result_rep = str_rep.replace(/blue/gi, "red"); document.getElementById("replace7").innerHTML = result_rep; let result_rep2 = str_rep.replace(/blue|house|car/gi, function (x) { return x.toUpperCase(); }); document.getElementById("replace8").innerHTML = result_rep2; function myFunction2(){ var str = document.getElementById('method13').innerHTML; var txt = str.replace("Microsoft", "my website"); document.getElementById("method13").innerHTML = txt; } function myFunction3(){ var str = document.getElementById('method14').innerHTML; var txt = str.replace(/MICROSOFT/i, "my website"); document.getElementById("method14").innerHTML = txt; } function myFunction4(){ var str = document.getElementById('method15').innerHTML; var txt = str.replace(/Microsoft/g, "my website"); document.getElementById("method15").innerHTML = txt; } </script>
Syntax: string.search(searchValue)
Parameters:
searchValue: required. The search value. A regular expression (or a string that will be converted to a regular expression).
The search() method matches a string against a regular expression. If the search value is a string, it is converted to a regular expression. The search() method returns the index (position) of the first match and returns -1 if no match is found. It is case sensitive.
Examples
<div class="spec"> <a id="search1"></a><br><br> <a id="search2"></a><br> <a id="search3"></a><br> <a id="search4"></a><br> <a id="search5"></a><br> <a id="search6"></a><br> <a id="search7"></a><br> </div> <script> var str = "Please locate where 'locate' occurs!"; var pos = str.search("locate"); document.getElementById("search1").innerHTML = str + " : " + pos + "th position"; let text_o = "Mr. Blue has a blue house" document.getElementById('search2').innerHTML = text_o; let position = text_o.search("Blue"); document.getElementById("search3").innerHTML = "'Blue' position : " + position; let position1 = text_o.search("blue"); document.getElementById("search4").innerHTML = "'blue' position : " + position1; let position2 = text_o.search(/Blue/); document.getElementById("search5").innerHTML = "'/Blue/' position : " + position2; let position3= text_o.search(/blue/); document.getElementById("search6").innerHTML = "'/blue/' position : " + position3; let position4 = text_o.search(/blue/i); document.getElementById("search7").innerHTML = "'/blue/i' position : " + position4; </script>
Syntax: string.slice(start, end)
Parameters:
start: required. The start position. (First character is 0) ;
end: optional. The end position (up to, but not including). Default is string length.
The method takes 2 parameters: the start position, and the end position (end not included). If a parameter is negative, the position is counted from the end of the string. If you omit the second parameter, the method will slice out the rest of the string.
The slice() method returns the extracted part in a new string. It does not change the original string. The start and end parameters specifies the part of the string to extract. The first position is 0, the second is 1, ... A negative number selects from the end of the string.
Examples
<div class="spec"> <a id="slice1"></a><br> <a id="slice2"></a><br> <a id="slice3"></a><br> <a id="slice4"></a><br> <a id="slice5"></a><br> <a id="slice6"></a><br> <a id="slice7"></a><br> </div> <script> var str_a = "Apple, Banana, Kiwi"; var res_a = str_a.slice(7, 13); document.getElementById("slice1").innerHTML = "1/ sliced section: " + res_a; var res_b = str_a.slice(-12, -6); document.getElementById("slice2").innerHTML = "2/ sliced section: " + res_b; var res_c = str_a.slice(7); document.getElementById("slice3").innerHTML = "3/ sliced section: " + res_c; var res_d = str_a.slice(-12); document.getElementById("slice4").innerHTML = "4/ sliced section: " + res_d; </script>
<div class="spec"> <a id="slice8"></a><br> <a id="slice9"></a><br> <a id="slice10"></a><br> <a id="slice11"></a><br> <a id="slice12"></a><br> <a id="slice13"></a><br> <a id="slice14"></a><br> </div> <script> let text_s = "Hello world!"; let result_s = text_s.slice(0, 5); document.getElementById("slice8").innerHTML = "slice 0-5: " + result_s; let result_ss = text_s.slice(3); document.getElementById("slice9").innerHTML = "slice 3: " + result_ss; let result_s3 = text_s.slice(3, 8); document.getElementById("slice10").innerHTML = "slice 3-8: " + result_s3; let result_s4 = text_s.slice(0,1); document.getElementById("slice11").innerHTML = "slice 0-1: " + result_s4; let result_s5 = text_s.slice(-1); document.getElementById("slice12").innerHTML = "slice -1: " + result_s5; let result_s6 = text_s.slice(0); document.getElementById("slice13").innerHTML = "slice 0: " + result_s6; </script>
Syntax: string.split(separator, limit)
Parameters:
separator: optional. A string or regular expression to use for splitting. If omitted, an array with the original string is returned.;
limit: optional. An integer that limits the number of splits. Items after the limit are excluded.
If the separator is omitted, the returned array will contain the whole string in index [0]. If the separator is "", the returned array will be an array of single characters.
Examples
<div class="spec"> <p>Click "Try it" to display the first array element, after a string split.</p> <button onclick="myFunction10()">Try it</button><br> <a id="split1"></a><br> <a id="split2"></a><br> </div> <script> function myFunction10() { var str = "a,b,c,d,e,f"; var arr = str.split(","); document.getElementById("split1").innerHTML = arr[0] + " - " + arr[2] + " - " + arr[4] ; } var str = "Hello"; var arr = str.split(""); var text = ""; var i; for (i = 0; i < arr.length; i++) { text += arr[i] + " - " } document.getElementById("split2").innerHTML = text; </script>
<div class="spec"> <a id="split3"></a><br> <a id="split4"></a><br> <a id="split5"></a><br> <a id="split6"></a><br> <a id="split7"></a><br> <a id="split8"></a><br> <a id="split9"></a><br> </div> <script> let text_aa = "How are you doing today?"; const array_1 = text_aa.split(" "); document.getElementById("split3").innerHTML = array_1; const array_2 = text_aa.split(" "); document.getElementById("split4").innerHTML = array_2[1]; const array_3 = text_aa.split(""); document.getElementById("split5").innerHTML = array_3; const array_4 = text_aa.split(" ", 3); document.getElementById("split6").innerHTML = array_4; const chars = text_aa.split(""); document.getElementById("split7").innerHTML = chars[1]; const array_5 = text_aa.split("o"); document.getElementById("split8").innerHTML = array_5; const array_6 = text_aa.split(); document.getElementById("split9").innerHTML = array_6; </script>
Syntax: string.startsWith(searchValue, start)
Parameters:
searchValue: required. The string to search for.;
start: optional. Start position. Default is 0.
The startsWith() method is case sensitive.
Examples
<div class="spec"> <a id="start1"></a><br> <a id="start2"></a><br> </div> <script> let text_ab = "Hello world, welcome to the universe."; let result_st1 = text_ab.startsWith("Hello"); document.getElementById("start1").innerHTML = "starts wih 'Hello' : " + result_st1; let result_st2 = text_ab.startsWith("world", 7); document.getElementById("start2").innerHTML = "starts wih 'world' : " +result_st2; </script>
Syntax: string.substr(start, length)
Parameters:
start: required. The start position. First character is at index 0. If start is greater than the length, substr() returns "". If start is negative, substr() counts from the end of the string.;
length: optional. The number of characters to extract. If omitted, it extracts the rest of the string
The substr() method extracts a part of a string. It begins at a specified position, and returns a specified number of characters. It does not change the original string. To extract characters from the end of the string, use a negative start position..
Examples
<div class="spec"> <a id="sub1"></a><br> <a id="sub2"></a><br> <a id="sub3"></a><br> <a id="sub4"></a><br> <a id="sub5"></a><br> <a id="sub6"></a><br> <a id="sub7"></a><br> <a id="sub8"></a><br> </div> <script> var str_cc = "Apple, Banana, Kiwi"; var res_cc = str_cc.substr(7, 6); document.getElementById("sub1").innerHTML = "1/ substr: " + res_cc; var res_cd = str_cc.substr(7); document.getElementById("sub2").innerHTML = "2/ substr: " + res_cd; var res_ce = str_cc.substr(-4); document.getElementById("sub3").innerHTML = "3/ substr: " + res_ce; let text_dd = "Hello world!"; let result_dd = text_dd.substr(1, 4); document.getElementById("sub4").innerHTML = "substring 1-4 : " + result_dd; let result_de = text_dd.substr(2); document.getElementById("sub5").innerHTML = "substring 2 : " + result_de; let result_df = text_dd.substr(0, 1); document.getElementById("sub6").innerHTML = "substring 0-1 : " + result_df; let result_dg = text_dd.substr(text_dd.length-1, 1); document.getElementById("sub7").innerHTML = "substring length -1,1 : " + result_dg; let result_dh = text_dd.substr(-6, 6); document.getElementById("sub8").innerHTML = "substring -6-6 : " + result_dh; </script>
Syntax: string.substring(start, end)
Parameters:
start: required. Start position. First character is at index 0.;end: optional. End position (up to, but not including). If omitted: the rest of the string.
The substring() method extracts characters from start to end (exclusive). It does not change the original string. If start is greater than end, arguments are swapped: (4, 1) = (1, 4). Start or end values less than 0, are treated as 0.
Similar to slice() but substring() cannot accept negative indexes.
Examples
<div class="spec"> <a id="substring1"></a><br> <a id="substring2"></a><br> <a id="substring3"></a><br> <a id="substring4"></a><br> <a id="substring5"></a><br> <a id="substring6"></a><br> <a id="substring7"></a><br> <a id="substring8"></a><br> </div> <script> var str_ee = "Apple, Banana, Kiwi"; var res_ee = str_ee.substring(7, 13); document.getElementById("substring1").innerHTML = "1/ substring: " + res_ee; let text_ef = "Hello world!"; let result_ef = text_ef.substring(1, 4); document.getElementById("substring2").innerHTML = "2/ substring: " + result_ef; let result_eg = text_ef.substring(2); document.getElementById("substring3").innerHTML = "3/ substring: " + result_eg; let result_eh = text_ef.substring(4, 1); document.getElementById("substring4").innerHTML = "4/ substring: " + result_eh; let result_ei = text_ef.substring(-3); document.getElementById("substring5").innerHTML = "5/ substring: " + result_ei; let result_ej = text_ef.substring(0,1); document.getElementById("substring6").innerHTML = "6/ substring: " + result_ej; let result_ek = text_ef.substring(text_ef.length -1); document.getElementById("substring7").innerHTML = "7/ substring: " + result_ek; </script>
Syntax: string.toLocaleLowerCase()
Parameters: none
The locale is based on the language settings of the browser. The toLocaleLowerCase() method does not change the original string. It returns the same result as toLowerCase(), except for locales that conflict with the regular Unicode case mappings (such as Turkish).
Examples
<div class="spec"> <p id="locale1"></p> <p id="locale2"></p> <p id="locale3"></p> <p id="locale4"></p> </div> <script> let text_tt = "Hello World!"; let result_tt = text_tt.toLocaleLowerCase(); document.getElementById("locale1").innerHTML = text_tt + " -> " + result_tt; let text_tu = "NEVER AGAIN!"; let result_tu = text_tu.toLocaleLowerCase(); document.getElementById("locale2").innerHTML = text_tu + " -> " + result_tu; let text_tv = "NiCe To MeEt YoU!"; let result_tv = text_tv.toLocaleLowerCase(); document.getElementById("locale3").innerHTML = text_tv + " -> " + result_tv; </script>
Syntax: string.toLocaleUpperCase()
Parameters: none
The locale is based on the language settings of the browser. It does not change the original string. It returns the same result as toUpperCase(), except for locales that conflict with the regular Unicode case mappings (such as Turkish).
Examples
<div class="grid"> <div class="spec"> <p id="locale5"></p> <p id="locale6"></p> <p id="locale7"></p> <p id="locale8"></p> </div> <script> let text_rr = "Hello World!"; let result_rr = text_rr.toLocaleUpperCase(); document.getElementById("locale5").innerHTML = text_rr + " -> " + result_rr; let text_rs = "never again!"; let result_rs = text_rs.toLocaleUpperCase(); document.getElementById("locale6").innerHTML = text_rs + " -> " + result_rs; let text_rt = "NiCe To MeEt YoU!"; let result_rt = text_rt.toLocaleUpperCase(); document.getElementById("locale7").innerHTML = text_rt + " -> " + result_rt; </script>
Syntax: string.toLowerCase()
Parameters: none
The toLowerCase() method does not change the original string.
Examples
<div class="spec"> <button onclick="myFunction6()">Try it</button><br> <a id="lower1">Hello Blue PLANET</a><br><br> <a id="lower2"></a><br> <a id="lower3"></a><br> <a id="lower4"></a><br> <a id="lower5"></a><br> </div> <script> function myFunction6() { var text_11 = document.getElementById("lower1").innerHTML; document.getElementById("lower1").innerHTML = text_11.toLowerCase(); } let text_12 = "Hello World!"; let result_12 = text_12.toLowerCase(); document.getElementById("lower3").innerHTML = text_12 + " -> " + result_12; let text_13 = "NEVER AGAIN!"; let result_13 = text_13.toLowerCase(); document.getElementById("lower4").innerHTML = text_13 + " -> " + result_13; let text_14 = "NiCe To MeEt YoU!"; let result_14 = text_14.toLowerCase(); document.getElementById("lower5").innerHTML = text_14 + " -> " + result_14; </script>
Syntax: string.toString()
Parameters: none
The toString() method does not change the original string and can be used to convert a string object into a string.
Examples
<div class="spec"> <p id="string1"></p> <p id="string2"></p> <p id="string3"></p> </div> <script> let text_22 = "Hello World!"; let result_22 = text_22.toString(); document.getElementById("string1").innerHTML = result_22; let result_23 = text_22; document.getElementById("string2").innerHTML = result_23; let text_33 = new String("Hello World!"); let result_33 = text_33.toString(); document.getElementById("string3").innerHTML = result_33; </script>
Syntax: string.toUpperCase()
Parameters: none
The toUpperCase() method does not change the original string.
Examples
<div class="spec"> <button onclick="upperF()">Try it</button><br> <a id="upper1">Hello World</a><br><br> <a id="upper2"></a><br> <a id="upper3"></a><br> <a id="upper4"></a><br> </div> <script> function upperF() { var text = document.getElementById("upper1").innerHTML; document.getElementById("upper1").innerHTML = text.toUpperCase(); } let text_44 = "Hello World!"; let result_44 = text_44.toUpperCase(); document.getElementById("upper2").innerHTML = text_44 + " -> " + result_44; let text_45 = "never again!"; let result_45 = text_45.toUpperCase(); document.getElementById("upper3").innerHTML = text_45 + " -> " + result_45; let text_46 = "NiCe To MeEt YoU!"; let result_46 = text_46.toUpperCase(); document.getElementById("upper4").innerHTML = text_46 + " -> " + result_46; </script>
Capitalize a string: JavaScript does not have a built-in function to capitalize string, but workarounds can help to obtain the goal.
Example - code
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1); console.log(capitalize('hello world')); // Hello world
const capitalize = str => `${str.charAt(0).toUpperCase()}${str.slice(1)}`; capitalize("hello, you are a cool person!"); // Result: "Hello, you are a cool person!"
const capitalize = ([first, ...rest]) => `${first.toUpperCase()}${rest.join('')}`; capitalize('hello world'); // 'Hello world'
Syntax: string.trim()
Parameters: none
The trim() method does not change the original string.
Examples
<div> <pre style="border:none"><p id="trim1"></p></pre> <pre style="border:none"><p id="trim2"></p></pre> <pre style="border:none"><p id="trim3"></p></pre> <pre style="border:none"><p id="trim4"></p></pre> </div> <script> let text_55 = " Hello World! "; let result_55 = text_55.trim(); document.getElementById("trim1").innerHTML = text_55; document.getElementById("trim2").innerHTML = result_55; let result_56 = text_55.replace(/^\s+|\s+$/gm,''); document.getElementById("trim3").innerHTML = text_55; document.getElementById("trim4").innerHTML = result_56; </script>
Syntax: string.trimEnd()
Parameters: none
The trimEnd() method does not change the original string. It works like trim(), but removes whitespace only from the end of a string.
Examples
<div> <p id="trim5"></p> </div> <script> let text_57 = " Hello World! "; let text_58 = text_57.trimEnd(); document.getElementById("trim5").innerHTML = "Length text_57 = " + text_57.length + "<br>Length text_58 = " + text_58.length; </script>
Syntax: string.trimStart()
Parameters: none
The trimStart() method does not change the original string. It works like trim(), but removes whitespace only from the start of a string.
Examples
<div> <p id="trim6"></p> </div> <script> let text_59 = " Hello World! "; let text_60 = text_59.trimStart(); document.getElementById("trim6").innerHTML = "Length text_59 = " + text_59.length + "<br>Length text_60 = " + text_60.length; </script>
Syntax: string.valueOf()
Parameters: none
The valueOf() method does not change the original string and can be used to convert a string object into a string.
Example:
<div> <p id="value1"></p> <p id="value2"></p> </div> <script> let text_70 = "Hello World!"; let result_70 = text_70.valueOf(); document.getElementById("value1").innerHTML = result_70; let result_71 = text_70; document.getElementById("value2").innerHTML = result_71; </script>
Both methods accept a second parameter as the starting position for the search.
Examples
<div class="spec"> <a id="remark1"></a> </div> <script> var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate",25); document.getElementById("remark1").innerHTML = str + " : " + pos + "th position"; </script>
So, position 15 means start the search at position 15, and search to the beginning.
Examples
<div class="spec "> <a id="remark2"></a> </div> <script> var str = "Please locate where 'locate' occurs!"; var pos = str.lastIndexOf("locate",15); document.getElementById("remark2").innerHTML = str + " : " + pos + "th position"; </script>
They however are different, as the search() method cannot take a second start position argument and the indexOf() method cannot take powerful search values (regular expressions).
Instead of ' ' or " " quotation marks, template strings use the backticks (` `). They offer a much better way of string interpolation and expressions can be embedded in a way like ${a+b}. It offers a much nicer syntax than the + operator.
You can use multi-line strings and string interpolation features with them. Instead of using the + operator to concatenate strings we can use ES6 template literals.
longhand
const welcome = 'You have logged in as ' + first + ' ' + last + '.' const db = 'http://' + host + ':' + port + '/' + database; const welcome = "Hi "+ firstName + " " + lastName + "."
shorthand
const welcome = `You have logged in as ${first} ${last}`; const db = `http://${host}:${port}/${database}`; const welcome = `Hi ${firstName} ${lastName}`;
template literals, template strings, string templates, back-tics syntax.
Template strings use back-ticks (``) rather than the quotes ("") to define a string. With template literals, you can use both single and double quotes inside a string. Template literals also allow multiline strings and they allow expressions in strings.
${...}
Click on the above button to add two numbers and display them.
<div class="spec"> <button style="margin-left:5vw;"class="Btn">click me</button> <p class="spec" style="margin-left:6vw;">Click on the above button to add two numbers and display them.</p> <div class="result" style="margin-left:5vw;color:blueviolet"></div> </div> <script> let resEle = document.querySelector(".result"); let a = 22; let b = 44; function add(a, b) { return a + b; } document.querySelector(".Btn").addEventListener("click", () => { resEle.innerHTML = `The sum of ${a} and ${b} = ${add(a, b)}`; }); </script>
<div class="spec"> <p class="spec" id="demoAA"></p> </div> <script> let firstName1 = "John"; let lastName1 = "Doe"; let textAA = `Welcome ${firstName1}, ${lastName1}!`; document.getElementById("demoAA").innerHTML = textAA; </script>
<div class="spec"> <p class="spec" id="demo-01"></p> </div> <script> let price = 10; let VAT = 0.25; let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`; document.getElementById("demo-01").innerHTML = total; </script>
<div class="spec"> <p id="template1"></p> </div> <script> let header = "Templates Literals"; let tags = ["template literals", "javascript", "es6"]; let html = `<h4>${header}</h4><ul>`; for (const x of tags) { html += `<li>${x}</li>`; } html += `</ul>`; document.getElementById("template1").innerHTML = html; </script>
<div class="spec"> <a id="ex1"></a><br><br> <a id="ex2"></a><br><br> <a id="ex3"></a><br><br> <a id="ex4"></a><br><br> <a id="ex4a"></a><br><br> <a id="ex4b"></a><br><br> </div> <script> let firstName = 'Lou'; let lastName = 'Grant'; let fullName = firstName + ' ' + lastName; document.getElementById('ex1').innerHTML = "concatenate first and last name :" + fullName; document.getElementById('ex2').innerHTML = "index[0] of full name: " + fullName[0]; document.getElementById('ex3').innerHTML = "index[3] of full name: " + fullName[4]; document.getElementById('ex4').innerHTML = "full name length: " + (fullName.length); document.getElementById('ex4a').innerHTML = "full name to uppercase: " + fullName.toUpperCase(); let result = fullName.toLowerCase(); document.getElementById('ex4b').innerHTML = (result, fullName);
<div class="spec"> <a id="ex5"></a><br> <a id="ex6"></a> </div> <script> let doh = "experiment"; document.getElementById('ex5').innerHTML = (typeof doh.toUpperCase); document.getElementById('ex6').innerHTML = (doh.toUpperCase()); </script>
<div class="spec"> <a id="ex7"></a><br><br> <a id="ex8"></a><br><br> <a id="ex9"></a><br><br> <a id="ex10"></a><br><br> <a id="ex11"></a><br><br> <a id="ex12"></a><br><br> <a id="ex13"></a><br><br> <a id="ex14"></a> </div> <script> let email = '[email protected]'; let index = email.indexOf('@'); document.getElementById('ex7').innerHTML = "indexOf: " + index; var pos = str.indexOf("lo"); let result1 = email.lastIndexOf('o'); let result2 = email.slice(0, 10); let result3 = email.slice(0, 5); let result4 = email.substr(4,10); let result5 = email.replace('o', 'e'); let result6 = email.replace('i', 'a'); document.getElementById('ex8').innerHTML = "indexOf: " + pos; document.getElementById('ex9').innerHTML = "lastIndexOf: " + result1; document.getElementById('ex10').innerHTML = "slice: " + result2; document.getElementById('ex11').innerHTML = "slice: " + result3; document.getElementById('ex12').innerHTML = "substr: " + result4; document.getElementById('ex13').innerHTML = "replace o with e: " + result5; document.getElementById('ex14').innerHTML = "replace i with a: " + result6; </script>
<div class="spec"> <a id="ex15"></a><br> <a id="ex16"></a><br> <a id="ex17"></a> </div> <script> let str2 = `Hello`; document.getElementById('ex15').innerHTML = "character at index[0]: " + str2.charAt(0); document.getElementById('ex16').innerHTML = "last character: " + str[str.length - 1]; let str3 = 'As sly as a fox, as strong as an ox'; let target = 'as'; let pos1 = 0; while (true) { let foundPos = str3.indexOf(target, pos1); if (foundPos == -1) break; document.getElementById('ex17').innerHTML = `Found at ${foundPos}`; pos1 = foundPos + 1; // continue the search from the next position } </script>
const sentence = 'The quick brown fox jumps over the lazy dog.'; const index = 4; console.log(`The character at index ${index} is ${sentence.charAt(index)}`); // expected output: "The character at index 4 is q"
const sentence = 'The quick brown fox jumps over the lazy dog.'; const index = 4; console.log(`The character code ${sentence.charCodeAt(index)} is equal to ${sentence.charAt(index)}`); // expected output: "The character code 113 is equal to q"
const icons = '☃★♲'; console.log(icons.codePointAt(1)); // expected output: "9733"
const str1 = 'Hello'; const str2 = 'World'; console.log(str1.concat(' ', str2)); // expected output: "Hello World" console.log(str2.concat(', ', str1)); // expected output: "World, Hello"
const str1 = 'Cats are the best!'; console.log(str1.endsWith('best', 17)); // expected output: true const str2 = 'Is this a question'; console.log(str2.endsWith('?')); // expected output: false
console.log(String.fromCharCode(189, 43, 190, 61)); // expected output: "½+¾="
console.log(String.fromCodePoint(9731, 9733, 9842, 0x2F804)); // expected output: "☃★♲你"
const sentence = 'The quick brown fox jumps over the lazy dog.'; const word = 'fox'; console.log(`The word "${word}" ${sentence.includes(word) ? 'is' : 'is not'} in the sentence`); // expected output: "The word "fox" is in the sentence"
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?'; const searchTerm = 'dog'; const indexOfFirst = paragraph.indexOf(searchTerm); console.log(`The index of the first "${searchTerm}" from the beginning is ${indexOfFirst}`); // expected output: "The index of the first "dog" from the beginning is 40" console.log(`The index of the 2nd "${searchTerm}" is ${paragraph.indexOf(searchTerm, (indexOfFirst + 1))}`); // expected output: "The index of the 2nd "dog" is 52"
const a = 'réservé'; // with accents, lowercase const b = 'RESERVE'; // no accents, uppercase console.log(a.localeCompare(b)); // expected output: 1 console.log(a.localeCompare(b, 'en', { sensitivity: 'base' })); // expected output: 0
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.'; const regex = /[A-Z]/g; const found = paragraph.match(regex); console.log(found); // expected output: Array ["T", "I"]
let regexp = /t(e)(st(\d?))/g; let str = 'test1test2'; let array = [...str.matchAll(regexp)]; console.log(array[0]); // expected output: Array ["test1", "e", "st1", "1"] console.log(array[1]); // expected output: Array ["test2", "e", "st2", "2"]
const name1 = '\u0041\u006d\u00e9\u006c\u0069\u0065'; const name2 = '\u0041\u006d\u0065\u0301\u006c\u0069\u0065'; console.log(`${name1}, ${name2}`); // expected output: "Amélie, Amélie" console.log(name1 === name2); // expected output: false console.log(name1.length === name2.length); // expected output: false const name1NFC = name1.normalize('NFC'); const name2NFC = name2.normalize('NFC'); console.log(`${name1NFC}, ${name2NFC}`); // expected output: "Amélie, Amélie" console.log(name1NFC === name2NFC); // expected output: true console.log(name1NFC.length === name2NFC.length); // expected output: true
const str1 = 'Breaded Mushrooms'; console.log(str1.padEnd(25, '.')); // expected output: "Breaded Mushrooms........" const str2 = '200'; console.log(str2.padEnd(5)); // expected output: "200 "
const str1 = '5'; console.log(str1.padStart(2, '0')); // expected output: "05" const fullNumber = '2034399002125581'; const last4Digits = fullNumber.slice(-4); const maskedNumber = last4Digits.padStart(fullNumber.length, '*'); console.log(maskedNumber); // expected output: "************5581"
// Create a variable that uses a Windows // path without escaping the backslashes: const filePath = String.raw`C:\Development\profile\aboutme.html`; console.log(`The file was uploaded from: ${filePath}`); // expected output: "The file was uploaded from: C:\Development\profile\aboutme.html"
const chorus = 'Because I\'m happy. '; console.log(`Chorus lyrics for "Happy": ${chorus.repeat(27)}`); // expected output: "Chorus lyrics for "Happy": Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. Because I'm happy. "
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'; const regex = /dog/gi; console.log(p.replace(regex, 'ferret')); // expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?" console.log(p.replace('dog', 'monkey')); // expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'; const regex = /dog/gi; console.log(p.replaceAll(regex, 'ferret')); // expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?" console.log(p.replaceAll('dog', 'monkey')); // expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?'; // any character that is not a word character or whitespace const regex = /[^\w\s]/g; console.log(paragraph.search(regex)); // expected output: 43 console.log(paragraph[paragraph.search(regex)]); // expected output: "."
const str = 'The quick brown fox jumps over the lazy dog.'; console.log(str.slice(31)); // expected output: "the lazy dog." console.log(str.slice(4, 19)); // expected output: "quick brown fox" console.log(str.slice(-4)); // expected output: "dog." console.log(str.slice(-9, -5)); // expected output: "lazy"
const str = 'The quick brown fox jumps over the lazy dog.'; const words = str.split(' '); console.log(words[3]); // expected output: "fox" const chars = str.split(''); console.log(chars[8]); // expected output: "k" const strCopy = str.split(); console.log(strCopy); // expected output: Array ["The quick brown fox jumps over the lazy dog."]
const str1 = 'Saturday night plans'; console.log(str1.startsWith('Sat')); // expected output: true console.log(str1.startsWith('Sat', 3)); // expected output: false
const str = 'Mozilla'; console.log(str.substr(1, 2)); // expected output: "oz" console.log(str.substr(2)); // expected output: "zilla"
const str = 'Mozilla'; console.log(str.substring(1, 3)); // expected output: "oz" console.log(str.substring(2)); // expected output: "zilla"
const dotted = 'İstanbul'; console.log(`EN-US: ${dotted.toLocaleLowerCase('en-US')}`); // expected output: "i̇stanbul" console.log(`TR: ${dotted.toLocaleLowerCase('tr')}`); // expected output: "istanbul"
const city = 'istanbul'; console.log(city.toLocaleUpperCase('en-US')); // expected output: "ISTANBUL" console.log(city.toLocaleUpperCase('TR')); // expected output: "İSTANBUL"
const sentence = 'The quick brown fox jumps over the lazy dog.'; console.log(sentence.toLowerCase()); // expected output: "the quick brown fox jumps over the lazy dog."
const stringObj = new String('foo'); console.log(stringObj); // expected output: String { "foo" } console.log(stringObj.toString()); // expected output: "foo"
const sentence = 'The quick brown fox jumps over the lazy dog.'; console.log(sentence.toUpperCase()); // expected output: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."
const greeting = ' Hello world! '; console.log(greeting); // expected output: " Hello world! "; console.log(greeting.trim()); // expected output: "Hello world!";
const greeting = ' Hello world! '; console.log(greeting); // expected output: " Hello world! "; console.log(greeting.trimEnd()); // expected output: " Hello world!";
const greeting = ' Hello world! '; console.log(greeting); // expected output: " Hello world! "; console.log(greeting.trimStart()); // expected output: "Hello world! ";
const stringObj = new String('foo'); console.log(stringObj); // expected output: String { "foo" } console.log(stringObj.valueOf()); // expected output: "foo"
let guestList = "Guests:\n * John\n * Pete\n * Mary"; alert(guestList); // a multiline list of guests let str1 = "Hello\nWorld"; // two lines using a "newline symbol" // two lines using a normal newline and backticks let str2 = `Hello World`; alert(str1 == str2); // true alert( `The backslash: \\` ); // The backslash: \ alert( 'I\'m the Walrus!' ); // I'm the Walrus!
alert( `My\n`.length ); // 3
let str = `Hello`; // the first character alert( str[0] ); // H alert( str.at(0) ); // H // the last character alert( str[str.length - 1] ); // o alert( str.at(-1) ); let str = `Hello`; alert( str[-2] ); // undefined alert( str.at(-2) ); // l for (let char of "Hello") { alert(char); // H,e,l,l,o (char becomes "H", then "e", then "l" etc) }
let str = 'Hi'; str[0] = 'h'; // error alert( str[0] ); // doesn't work let str = 'Hi'; str = 'h' + str[1]; // replace the string alert( str ); // hi
alert( 'Interface'.toUpperCase() ); // INTERFACE alert( 'Interface'.toLowerCase() ); // interface
let str = 'Widget with id'; alert( str.indexOf('Widget') ); // 0, because 'Widget' is found at the beginning alert( str.indexOf('widget') ); // -1, not found, the search is case-sensitive alert( str.indexOf("id") ); // 1, "id" is found at the position 1 (..idget with id) let str = 'Widget with id'; alert( str.indexOf('id', 2) ) // 12 let str = 'As sly as a fox, as strong as an ox'; let target = 'as'; // let's look for it let pos = 0; while (true) { let foundPos = str.indexOf(target, pos); if (foundPos == -1) break; alert( `Found at ${foundPos}` ); pos = foundPos + 1; // continue the search from the next position } let str = "As sly as a fox, as strong as an ox"; let target = "as"; let pos = -1; while ((pos = str.indexOf(target, pos + 1)) != -1) { alert( pos ); } let str = "Widget with id"; if (str.indexOf("Widget") != -1) { alert("We found it"); // works! }
alert( "Widget with id".includes("Widget") ); // true alert( "Hello".includes("Bye") ); // false alert( "Widget".includes("id") ); // true alert( "Widget".includes("id", 3) ); // false, from position 3 there is no "id" alert( "Widget".startsWith("Wid") ); // true, "Widget" starts with "Wid" alert( "Widget".endsWith("get") ); // true, "Widget" ends with "get"
let str = "stringify"; alert( str.slice(0, 5) ); // 'strin', the substring from 0 to 5 (not including 5) alert( str.slice(0, 1) ); // 's', from 0 to 1, but not including 1, so only character at 0 alert( str.slice(2) ); // 'ringify', from the 2nd position till the end // start at the 4th position from the right, end at the 1st from the right alert( str.slice(-4, -1) ); // 'gif' let str = "stringify"; // these are same for substring alert( str.substring(2, 6) ); // "ring" alert( str.substring(6, 2) ); // "ring" // ...but not for slice: alert( str.slice(2, 6) ); // "ring" (the same) alert( str.slice(6, 2) ); // "" (an empty string) let str = "stringify"; alert( str.substr(2, 4) ); // 'ring', from the 2nd position get 4 characters alert( str.substr(-4, 2) ); // 'gi', from the 4th position get 2 characters
alert( 'a' > 'Z' ); // true alert( 'Österreich' > 'Zealand' ); // true // different case letters have different codes alert( "Z".codePointAt(0) ); // 90 alert( "z".codePointAt(0) ); // 122 alert( "z".codePointAt(0).toString(16) ); // 7a (if we need a hexadecimal value) alert( String.fromCodePoint(90) ); // Z alert( String.fromCodePoint(0x5a) ); // Z (we can also use a hex value as an argument) let str = ''; for (let i = 65; i <= 220; i++) { str += String.fromCodePoint(i); } alert( str ); // Output: // ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ // ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜ