"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Create JS function to remove spaces from giving string. ( Using core js and not in-built trim function.)

Create JS function to remove spaces from giving string. ( Using core js and not in-built trim function.)

Published on 2024-11-07
Browse:456

Create JS function to remove spaces from giving string. ( Using core js and not in-built trim function.)

const trim = (string) => {
    let strArr = string.split("");
    let trimedStr = [];
    strArr.forEach((item) => {
      if (item !== " ") {
        trimedStr.push(item);
      }
    });
    return trimedStr.join("");
  };

  console.log("trim", trim("Hello world nice world"));
 // output => trim: Helloworldniceworld

Problem Explanation

Let's break down the problem in simple terms:

You have a piece of code that defines a function called trim. The purpose of this function is to remove all the spaces from a given string. In other words, if you pass a sentence with spaces into this function, it will return the same sentence but with all the spaces removed.

How the Function Works:

  1. Splitting the String: The function starts by taking the input string (e.g., "Hello world nice world") and splits it into an array of individual characters. For example, "Hello world" becomes ['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']...

  2. Filtering Out Spaces: The function then goes through each character in the array. If the character is not a space (' '), it adds it to a new array called trimedStr. If it is a space, it simply skips it.

  3. Rejoining the Characters: After filtering out the spaces, the function takes the remaining characters and joins them back together into a single string without any spaces.

  4. Returning the Result: Finally, the function returns the new string that has no spaces.

Release Statement This article is reproduced at: https://dev.to/ajaymarathe/create-js-function-to-remove-spaces-from-giving-string-26le?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3