Essential Guide to JavaScript String Manipulation

Essential Guide to JavaScript String Manipulation

ยท

3 min read

What is a string?

In programming language, a string is a collection of alphabets like "mohit" is a string and It is the one of the fundamental data types that is used to store and manipulate text.

Strings are primitive datatype that means it is immutable that means once the value is declared as String, cannot be updated later.

String are written in quotes it may be either backticks, single quote or double quote. Everything written in the quotes will result as string no matter what it is like "123" is a string.

Creating String

Template Literal
It is a way to write string using either single ( ' ), double ( " " ) or backtick ( ```). IF we need to write the value of some variable and we have string enclosed in backtick then we use $ { variable_name }.
// First way
// using Template Literal
const str = 'Ram'
const str2 = "Love"
console.log(`${str} is ${Love}`) 
/* output -->
Ram is Love */
//second way
// using Object
let str = new String("abc")
console.log(str)

String Methods

Let's understand every method directly in practical. Theory will be shared as comments form

 const abc = "Kotlin"
  • Length

      console.log(abc.length) // 6
    
  • CharacterAccess

      console.log(abc.charAt(0)) // K
      // Returns the character at the given index.
    
      console.log(abc[0]) // K
      // alternative way to get the char at given index
    
      console.log(abc.charCodeAt(0)) // 75
      // Returns the Unicode code of the character at the given index
    
  • Concatenation

      // let's have another string
      let xyz = "Java"
      console.log(abc + " " + xyz) //Kotlin Java
    
      console.log(abc.concat(" " + xyz) // Kotlin Java
    
      console.log(abc + xyz) // KotlinJava
    
      console.log(abc.concat(xyz)) // KotlinJava
    
  • CaseManipulation

      console.log(abc.toUpperCase()) // KOTLIN
    
      console.log(abc.toLowerCase()) // kotlin
    
  • Substring Operations

      console.log(abc.slice(0,4)) // kotl
      /* str.slice(start, end):
       Returns a section of the string from start to end (excluding end) */
    
      console.log(abc.substring(0,4)) // kotl
      /* str.substring(start, end): 
      Similar to slice(), but allows negative indices */
    
      console.log(abc.substr(0,4)) // kotl
      /*str.substr(start, length): 
      Returns a section of the string of specified length 
      starting from start. */
    
  • Searching

      console.log(abc.indexOf('i')) // 4
      /* Returns the index of the first occurrence of 
      substring or -1 if not found. Index starting from 0 */
    
      const a = "aiini"
      console.log(a.lastIndexOf('i')) // 4 
      /* str.lastIndexOf(substring): 
      Returns the index of the last occurrence. */
    
  • Matching

      console.log(abc.includes('in')) // true
      /* str.includes(substring): 
      Returns true if substring is found. */
    
      console.log(abc.endsWith('in')) // true
      /* str.endsWith(substring): 
      Returns true if the string ends with substring. */
    
      console.log(abc.startsWith('J')) // false
      /* str.startsWith(substring): 
      Returns true if the string starts with substring. */
    
  • Replacement

      const replaced = abc.replace("Kotlin","JavaScript")
      console.log(replaced) //JavaScript
      /* str.replace(oldValue, newValue):
       Replaces the first occurrence of oldValue with newValue. */
    
      let o = "aiiiin"
      const replacedAll = o.replaceAll('i','j')
      console.log(replacedAll) // ajjjjn
      /* str.replaceAll(oldValue, newValue): 
      Replaces all occurrences. */
    
  • Splitting

      const hello = "hellow world"
      console.log(hello.split(' ')) // [ "hellow", "world" ]
    
      /* str.split(separator): 
      Splits the string into an array based on the separator. */
    
  • Trimming

      const hell = "     sdafadf    "
      console.log(hell.trim())  // sdafadf
      /* str.trim(): 
      Removes leading and trailing whitespace */
    
      console.log(hell.trimStart()) // sdafadf..... (dot are whitespace)
      /* str.trimStart(): 
      Removes leading whitespace. */
    
      console.log(hello.trimEnd()) // .....sdfadf
      /* str.trimEnd(): 
      Removes trailing whitespace. */
    

Immutability

Whatever function we have performed on will not change the original declared string. However it looks like we have updated the value but this is not actually true. In fact, the original string will pass the reference to others in order to be manipulated. Only references were changing not that string.


Congratulations!!!! you have mastered JavaScript Strings. ๐Ÿฅ‚


If I am able to create value in you then make sure to follow me on various platform.

Instagram

LinkedIn

Hashnode


Thank you for reading ๐Ÿค

Written By Mohit Soni

ย