JavaScript String Functions
var str = "this is a string";
console.log(str); // THIS WILL PRINT THE VARIABLE
var position = str.indexOf('is');
console.log(position)this function will give the first position of occurrence the given element.
IN THE GIVEN EXAMPLE ITS 2
THIS IS A STRING.
position = str.lastIndexOf('is');
console.log(position)this function will give the last position of occurrence the given element.
IN THE GIVEN EXAMPLE ITS 5
THIS IS A STRING.
Substring from a string// var substr = str.slice(1,7);
// var substr = str.substring(1,7);
var substr1 = str.substr(1,3);
console.log(substr1)THESE ARE THE WAYS OF SLICING A STRING
SLICE CAN TAKE -VE VALUE AS INPUT WHILE SUB STRING CAN'T
FIRST VALUE IS INCLUDED LAST IS NOT
// var replaced = str.replace('string', 'Harry');
// console.log(str)
// console.log(replaced)THESE ARE THE REPLACE VARIABLES THESE ARE USED TO REPLACE ELEMENTS FROM STRING
IN THE GIVEN CASE THE THE OUTPUT WILL BE
FOR STR
THIS IS A STRING
FOR REPLACED
THIS IS A HARRY
// console.log(str.toUpperCase()); // console.log(str.toLowerCase()); THIS WILL CONVERT TEXT TO UPPER AND LOWER CASE
// var newString = str.concat('New String')SIMILAR AS OUR "+" OPERATOR
// var strWithWhitespaces = " this contains whitespaces ";
// console.log(strWithWhitespaces)
// console.log(strWithWhitespaces.trim())THE TRIM FUNCTION WILL TRIM ALL THE EXTRA WHITE SPACES IN THE BEGINNING AND END OF THE STRING BUT NOT IN THE MIDDLE
// var char2 = str.charAt(2);
// var char2 = str.charCodeAt(2); // Not very important
// console.log(char2)WILL GIVE THE CHARACTER AT 2 AND IT'S CODE RESPECTIVELY
console.log(str[3])SAME AS ABOVE
Comments
Post a Comment