Notes
The length property returns the length of a string:
let text = "I am learning JavaScript";
document.write(text.length);
Output: 24
slice()
extracts a part of a string and returns the extracted part in a new string.
let str = "I am learning JavaScript";
document.write(str.slice(14,24));
Output: JavaScript
Note: JavaScript counts positions from zero. First position is 0.
If a parameter is negative, the position is counted from the end of the string.
let str = "I am learning JavaScript";
document.write(str.slice(-10));
Output: JavaScript
substring()
is same as slice()
but does not accept negative indexes.
let str = "I am learning JavaScript";
document.write(str.slice(5,13));
Output: learning
The replace()
method replaces a specified value with another value in a string:
let text = "I am learning Apex";
document.write(text.replace("Apex", "javaScript"));
Output: I am learning JavaScript.
Note: By default, the replace() method replaces only the first match and it's case sensitive.
A string is converted to upper case with toUpperCase()
:
let text = "JavaScript";
document.write(text.toUpperCase());
Output: JAVASCRIPT
A string is converted to lower case with toLowerCase()
:
let text = "JavaScript";
document.write(text.toLowerCase());
Output: javascript
concat()
joins two or more strings:
let text1 = "Will";
let text2 = "Smith";
document.write(text1.concat(" ",text2));
The trim() method removes whitespace from both sides of a string:
let txt = " Java Script";
document.write(txt.trim());
Output: Java Script