Removing White Spaces in a String Using JavaScript Manually

I have created my own algorithm to achieve the same outcome as this function:

var string= string.split(' ').join('');

For example, if I input the String: Hello how are you, it should become Hellohowareyou

My approach avoids using .replace, regex, or .split

However, upon testing, my algorithm does not seem to alter the original String:

var x = prompt("Enter String");

for (var i=0; i<=x.length;i++) {
     if (x[i] == " ") {
         x[i] = "";
     }
 }

alert(x);

Answer №1

Iterating through a string and skipping spaces while copying characters is the key to solving this challenge. It's important to note that strings in JavaScript are immutable, meaning you cannot directly change individual characters within a string using syntax like x[i] = 'c'.

For more information on the immutability of JavaScript strings and whether a "string builder" is needed, check out Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?

var string =  'Hello     How    are you';
var noSpaces = '';
for (var i = 0; i < string.length; i++) {
  if (string.charAt(i) != ' ' ) {
    noSpaces += string.charAt(i);
  }
}

alert(noSpaces);

Answer №2

The reason why your code is not functioning correctly is due to the fact that, particularly for strings, there isn't a setter available for the indexed approach (x[0] = "w"). Strings cannot be treated as arrays since they are a unique type of object (an immutable object) that can be accessed by index but lacks a setter in this context.

To correct your code, make the following changes:

var x = prompt("Enter sum or 'e' to Exit");
var modified = "";

for (var i=0; i<x.length;i++) {
     if (x[i] != " ") {
         modified += x[i];
     }
 }

alert(modified);

Alternatively, you can improve your code further by using regex as shown below:

var x = prompt("Enter sum or 'e' to Exit");
x = x.replace(/\s/g,"");

Answer №3

Your code is currently attempting to replace a value with the same variable, which is not possible. Instead, you should store the value in a new variable like this:

var input = prompt("Enter a number or 'e' to exit");
var result = '';
for (var index=0; index<input.length; index++) {
     if (input[index] != " ") {
         result += input[index];
     }
 }

alert(result);

You can check out the solution at this link https://jsfiddle.net/rqL3cvog/

Answer №4

One alternative method to update the variable x without using an additional variable involves implementing a reverse loop with the use of slice to extract the string before and after the specified index i:

var x = prompt("Please input a string");

for (var i = x.length; i--;) {
  if (x[i] == " ") {
    x = x.slice(0, i) + x.slice(i + 1, x.length);
  }
}

alert(x);

Alternatively, you can also utilize a backward for loop in conjunction with substr :-

var x = prompt("Please enter a string");

for (var i = x.length; i--;) {
  if (x[i] == " ") {
    x = x.substr(0, i) + x.substr(i + 1);
  }
}

alert(x);

Answer №5

Hello there,

I have provided the code below for your reference. It may seem lengthy, but feel free to ask for help to make it more concise. Please check the output.

var x = prompt("Hello       how   are   you");
y = ''
flag = false
for (var i=0; i<x.length;i++) {

  if (x[i] == " ") {
     flag= true
  }
  else {

     if (flag == true) {
         y += ' '
         y += x[i]
         flag = false
     }
     else {
         y += x[i] 
     }
  }
}

alert(y)

The output will be: "Hello how are you"

This code simply sets a flag when encountering a space in x[i]. Then, instead of adding whitespace, it adds a single space and the next character to the output string before setting the flag back to false.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript - Utilizing jQuery to dynamically add and remove input fields

I have a form where input fields (groups) are added dynamically. Here's a glimpse of the complex form: FIDDLE The error on the console reads: Error: uncaught exception: query function not defined for Select2 s2id_autogen1 With existing fields in t ...

Is there a way to print an HTML page in Landscape mode within my Vue.js project?

I have been able to successfully print an HTML page in Landscape mode using the code below. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,maximum-scale=1.0"> ...

React client side componentDidMount function encountering issues (server side rendering)

Greetings to the Stackoverflow community Apologies in advance if my explanation is not clear enough When a user directly types a URL, the server makes a request, fetches the corresponding data, and renders it on the screen flawlessly. However, when a us ...

What is the process for altering a route in React 18?

Previously, I relied on the withRouter Higher Order Component (HOC) along with props.history.push() function to manage routes. However, with the introduction of React 18, these options are no longer available. My current task involves editing a post and ...

Learn a valuable trick to activate CSS animation using a button - simply click on the button and watch the animation start over each time

I already know how to do this once. However, I would like the animation to restart or begin again when the user clicks on it a second time. Here is what I have: function animation() { document.getElementById('ExampleButton').className = &apo ...

Utilizing Typescript for parsing large JSON files

I have encountered an issue while trying to parse/process a large 25 MB JSON file using Typescript. It seems that the code I have written is taking too long (and sometimes even timing out). I am not sure why this is happening or if there is a more efficien ...

Mastering the art of utilizing callbacks in AngularJS for consuming an API

Having trouble handling data from an API and structuring it effectively before passing it to the controller. I've created a factory that retrieves user data from the API, but the provideAllUserData function is causing issues. Below is my services.js: ...

My JavaScript code is being executed before Chrome Auto-fill

I have successfully created form input elements in Chrome that display a floating label when focused. However, I am encountering an issue when the browser autofills the username and password fields with yellow prefilled text. The JavaScript for the float ...

Challenge with JavaScript personalized library

No matter how many times I review my code, I find myself perplexed. Despite my efforts to create a custom library of functions from scratch (shoutout to stackoverflow for guiding me on that), the results are leaving me puzzled. A javascript file is suppose ...

Adjust the badge's color based on the status retrieved from the jQuery AJAX call

I've been working on retrieving data from an endpoint through a get request, and I'm looking to adjust the color of the request status based on the response. $.ajax({ type: 'GET', url: 'api/v1/service/tax', succe ...

Arranging array elements by both date and alphabetical order using Javascript

Is there a way to sort the data by both date and alphabet at the same time? Alphabetical order seems fine, but the date sorting isn't working correctly. Thank you for any solutions. Data structure : [{ productId: 21, title: "Huawei P40 L ...

"Modifying state within a child component and utilizing the refreshed value in the parent component

I'm currently working on creating a simple header mini cart with a cart item counter in NextJS. I'm utilizing the form state value in the header component and then passing that value to the child components of the header where the numerical quant ...

Implementing a nested ng-repeat for organizing limited data

I'm working with a nested ng-repeat setup like this: <div ng-repeat="item_l in list1"> <div ng-repeat="item_f in list2"> {{item_f}} {{item_l}} </div> </div> Currently, this code is producing around 20 results. ...

Text randomly appears on the html page

I've been dedicating a significant amount of time to finding a solution, but haven't had any luck. I'm aiming to create a visual effect where 10 words with varying font sizes slide in from different directions on a canvas within my document ...

Ways to extract information from a JSON dataset

[{"id":7,"message":"This is just a sample message","taker_id":"131","giver_id":"102","status":"0","stamp":"2016-08-11"}] Here is my answer. I am attempting to retrieve some data. I have attempted using data.id but it is unsuccessful and gives me undefined ...

Switching effortlessly between Fixed and Relative positioning

As I work on creating a unique scrolling experience, I aim to have elements stop at specific points and animate before returning to normal scroll behavior once the user reaches the final point of the page. Essentially, when div X reaches the middle of the ...

Using Javascript in .NET to restrict the number of characters allowed in a textbox during typing and pasting

Consider this situation: I am attempting to display the indication "XY characters left" and restrict characters in a textbox as the user types. However, since I also have multiline textboxes, MaxLength doesn't always suffice (don't worry, I vali ...

extracting data from a javascript array

While facing an issue with scraping a website , I received helpful solutions from Fatherstorm and marcog. Despite the great solution provided by Fatherstorm, there were some minor bugs related to start time and the number of image sources being retrieved a ...

What is the syntax for populating an attribute on the same line as v-for in Vue.js?

I am currently working on a simple loop utilizing Vue to iterate over an array of objects and populate table rows. <tr v-for="user in users"> <td>{user.name}</td> <td>{user.id}</td> </tr> However, I also need to as ...

Copy values of multiple input fields to clipboard on click

I have a collection of buttons in my Library, each with different text that I want to copy when clicked function copyTextToClipboard(id) { var textElement = document.getElementById(id); textElement.select(); navigator.clipboard.writeText(textElement. ...