String Manipulation with JavaScript

JavaScript
  1. Split

    Split transforms a string into an array of substrings based on given delimiter.

    let str = "The dog jumped over the fence.";
    let substr = str.split(" ");
    console.log(substr); //["The", "dog", "jumped", "over", "the", "fence."]
    

    split can be given multiple delimiter using regular expression.

    let str = "I am counting my calories,yet I really want dessert.";
    let substr = str.split(/[" ",.]/);
    console.log(substr); //["I", "am", "counting", "my", "calories", "yet", "I", "really", "want", "dessert", ""]
    
  2. Slice

    It extracts a part of string between two given indices, the end index is exclusive.

    let str = "The dog jumped over the fence";
    let substr = str.slice(4,14);
    console.log(substr);//"dog jumped"
    

    For negative index, the index starts from the end of string.

    let str = "The dog jumped over the fence";
    let substr = str.slice(-9);
    console.log(substr); //"the fence"
    
  3. Replace

    The replace method as the name implies replace a part of string with the specified string.

    let str = "The dog jumped over the fence.The dog wagging its tail.";
    let substr = str.replace("dog","fox");
    console.log(substr);//"The fox jumped over the fence.The dog wagging its tail."
    

    In the above example, only the first “dog” has been replaced. To replace all “dog” in the sentence we have to use regular expression.

    let str = "The dog jumped over the fence.The dog wagging its tail.";
    let substr = str.replace(/dog/g,"fox");
    console.log(substr);//"The fox jumped over the fence.The fox wagging its tail."
    
  4. indexOf

    It searches for the occurrence of a value in a given string and returns the index where it is first found. If nothing is found, it returns -1.

    let str = "The dog jumped over the fence";
    let substr1 = str.indexOf("jumped"),
    substr2 = str.indexOf("cat")
    console.log(substr1," ",substr2);// 8 -1
    
  5. trim

    Removes all whitespaces from a string.

    let str = "   The dog jumped over the fence.   ";
    let substr = str.trim();
    console.log(substr); //"The dog jumped over the fence."
    

    In addition, there are two other methods called trimLeft() and trimRight() which removes all leading whitespaces from the right side.