3

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);
3
  • Following your edit (of not wanting to use replace, split or regular expressions), I've reopened the question. Commented Mar 2, 2016 at 13:49
  • Out of interest, why not use the right tool for the job? Is this specifically homework where youve been told to avoid those methods? Commented Mar 2, 2016 at 13:50
  • @Jamiec Yes, it's homework I made for myself - testing knowledge of Strings and For Loops Commented Mar 2, 2016 at 13:53

5 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

Up voted as this seems the best solution, though for older browsers see: string.charAt or string brackets?
@Roberto Yes, I've stopped caring about IE < 10 since IE stopped supporting it. microsoft.com/en-us/WindowsForBusiness/End-of-IE-support However, there is still some value in using charAt() still because using brackets does make you think you can set it.
Some of us still have to support enterprise apps running in IE compatibility mode. Usually IE7, but sometime even IE5. And unfortunately I don't see that going away soon because of the cost to covert these huge apps. :( Anyway, the comment was not intended to be negative.
@Roberto neither was mine, I'm just glad I don't have to worry about, it's a perfectly valid point.
3

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

5 Comments

You have to change for loop condition by doing i < x.length or by doing i <= x.length - 1 otherwise you'll get "undefined" at the end of the string
You should also explain why the original code doesn't work.
@Juhana Was typing it.
The word you're struggling for is immutable
@Jamiec Yes I was searching for an exact word. Thanks for the link.
2

In your code you just compare the value and try to replace with same variable but it's not possible to replace same with variable, just stored your value with new variable some thing like below

var x = prompt("Enter sum or 'e' to Exit");
var v='';
for (var i=0; i<x.length;i++) {
     if (x[i] != " ") {
         v +=x[i];
     }
 }

alert(v);

Here is the link https://jsfiddle.net/rqL3cvog/

4 Comments

You have an error. undefined is insert at the end of the string.
You have to change for loop condition by doing i < x.length or by doing i <= x.length - 1 otherwise you'll get "undefined" at the end of the string
@LucioB : Yes thank for correction, check it out i have updated my answer in loop " i < x.length".
up voted corrected solution, though this is now the equivalent of Juan's answer.
2

Another approach, which updates the variable x and does not use another variable is to use a reverse for loop and use slice to take the string before and after i:-

var x = prompt("Enter String");

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

alert(x);

Or, a reverse for loop with substr :-

var x = prompt("Enter String");

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

alert(x);

3 Comments

@JuanMendes - Im saying the same as you just said, basically saying "which updates x and does not build up a new value" is misleading at best, and just plain wrong at worst
@JuanMendes thats what I meant "the OP is only using one variable".
@Jamiec i've updated the explanation. sorry for the confusion.
-2

Hie ,

Please check below code. Its lengthy. But others can help to make it short. Check 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)

Output is : "Hello how are you"

Code just sets a flag when you get a space in x[i] & when you get next character its just add single space instead of whitespace & adds next character to output string & again sets flag to false.

4 Comments

Here is a wall of code without any explanation what it does or any explanation about what OP is doing wrong is something for on rentacoder.
@PeeHaa I have added the explanation
OP wants to strip all spaces?"Hello how are you it becomes Hellohowareyou" not Hello how are you
OP wants to remove whitespaces not all spaces. I know it's not smart & short code, but it works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.