Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually remove whitespace in String - JavaScript

Tags:

javascript

I have attempted to make an algorithm that will do the same thing as this function: var string= string.split(' ').join('');

So if I have the following String: Hello how are you it becomes Hellohowareyou

I don't want to use .replace or regex or .split

However, the algorithm doesn't seem to make any changes to the String:

var x = prompt("Enter String");

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

alert(x);
like image 436
SamG Avatar asked May 23 '26 19:05

SamG


2 Answers

Iterate over the string copying characters, skipping spaces. Your code doesn't work because strings are immutable, so you cannot change characters within the string by doing x[i] = 'c'.

See 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);
like image 160
Juan Mendes Avatar answered May 25 '26 08:05

Juan Mendes


Your code is not working because, probably for strings, similar to a getter, there is no setter for indexed approach(x[0] = "w"). You cannot consider a string as an array. Its a special form of object (immutable object) that can be accessed with index, but strictly there is no setter in this approach.

You can fix your code by changing like below,

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);

And you can do this in other better ways like below by using regex,

var x = prompt("Enter sum or 'e' to Exit");
x = x.replace(/\s/g,"");
like image 38
Rajaprabhu Aravindasamy Avatar answered May 25 '26 08:05

Rajaprabhu Aravindasamy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!