1. 程式人生 > >20 String methods in JS

20 String methods in JS

var stringOne = "freeCodeCamp is the best place to learn";
var StringTwo = "frontend and backend development";

//charAt()
console.log(stringOne.charAt(1)); // "r"

//charCodeAt()
console.log(stringOne.charCodeAt(1)); // 114

//concat()
    //it returns a new joined string
console.log(stringOne.concat(stringTwo));
    //"freeCodeCamp is the best place to learnfrontend and backend development"
//endsWith() console.log(stringOne.endsWith("learn")); // true //fromCharCode() console.log(String.fromCharCode(114)); // "r" //includes() console.log(stringTwo.includes("end")); // true //indexOf() //it returns the position of the first found occurrence of a specified value in a string console.log(stringTwo.indexOf("end"
)); // 5 //lastIndexOf() //it returns the position of the last found occurrence with a specified value in a string console.log(stringTwo.indexOf("end")); // 17 //match() //match is going to search a string for a match against a regular expression and returns the matches console.log(stringTwo.match(/end/g)); // ["end"
,"end"] //repeat() //it going to return a new string with a specified number of copies of an existing string console.log(stringTwo.repeat(2)); // "frontend and backend developmentfrontend and backend development" //replace() //it searched a string for a specified value or regular expression and returns a new string where the specified values are console.log(stringTwo.replace(/end/g, "END")); // frontEND and backEND development //search() //it's going to search a string for a specified value or regular expression and return the position of the match console.log(stringTwo.search("end")); // 5 //slice() //it's going to extract a part of the string and return a new string console.log(stringTwo.slice(2,4)); // "on" //split() //it's going to split a string into an array of sub strings console.log(stringTwo.split(" ")); // ["frontend","and","backend","development"] //startsWith() //it's going to check whether a string begins with specified characters consoe.log(stringOne.startsWith("free")); // true //substr() console.log(stringTwo.subStr(2,4)); // "onte" //substring() console.log(StringTwo.substring(2,4)) // "on" //toLowerCase() console.log(stringOne.toLowerCase()) // "freecodecamp is the best place to learn" //toUpperCase() console.log(stringOne.toUpperCase()) // "FREECODECAMP IS THE BEST PLACE TO LEARN" //trim() //it's going to remove whitespace from either side of the string var stringThree = " Subscribe now! " console.log(stringThree.trim()); // "Subscribe now!"