Strings and numbers in javascript

Strings in JavaScript

Important points to note about Strings are given below
  • Strings are primitive data types
  • Strings are passed by value
  • All strings inherit methods defined in String.prototype
  • Strings are immutable in JavaScript
  • Literal Strings do not have any methods of its own
  • Literal Strings inherit methods from String.prototype using Autoboxing process

String methods in JavaScript


//string methods

let name = "Harry Potter"

//get the length of string
console.log(name.length)
//output - 12

//replace the specific portion of string
console.log(name.replace("Harry","Tom"))
//output - Tom Potter

//replace the specific portion of string using regular expression
console.log(name.replace(/h.*y/i,"Tom"))
//output - Tom Potter

//remove all blank spaces from the string using regular expression
console.log("Remove space " + name.replace(/s/i,""))
//output - HarryPotter

//split the string
console.log(name.split(" ")[0])
//output - Harry

//search the substring
console.log(name.search(/arry/))
//output - 1

//search the substring using indexOf - 
//This method can not take regular expression
console.log(name.indexOf("arry"))
//output - 1

//extract substring starting from index
console.log(name.slice(6))
//output - Potter

//trim
console.log(name.trim())
//output - Harry Potter

//change case
console.log(name.toLowerCase())
//output - harry potter

Numbers in JavaScript


//Number methods

console.log(12 + 13)
//output - 25

console.log(12 + "13")
//output - 1213

console.log(12 + 0.3)
//output - 12.3

let x = 2.34344545;
console.log(x.toFixed(2))
//output - 2.34

console.log(x/"sd")
//output - NaN

console.log(x/0)
//output - Infinity


console.log(parseInt("234 fdf"))
//output - 234

console.log(parseInt(" fdf"))
//output - NaN

console.log(parseFloat("234.43 fdf"))
//output - 234.43

Complex problems, Simple Solutions