-1

I want to split a string in Java script using
str.split([separator[, limit]])

I want to split it by a space, but ' ' did not work. What should I use?

Teemu
  • 22,918
  • 7
  • 53
  • 106
Eowyn12
  • 199
  • 4
  • 4
    Can you please show the real code you have? Though most likely you're expecting `split` doing its job inplace, but it doesn't, it returns a new array instead of manipulating the original string. – Teemu Dec 12 '15 at 13:56

2 Answers2

1

This question has previously been asked here: How do I split a string, breaking at a particular character?

In your specific case, based on what you provided, it appears you are attempting to split on nothing. '' instead of an actual space ' '.

Community
  • 1
  • 1
Jim Clouse
  • 8,774
  • 6
  • 32
  • 25
0

To replace the spaces by commas:

var str = "How are you doing today?"; 
var res = str.split(" ");
//Output: How,are,you,doing,today?

Like described here: http://www.w3schools.com/jsref/jsref_split.asp

Another option is to use str.replace:

Var str = "Mr Blue has a blue house and a blue car";
var res = str.replace(/blue/gi, "red");
//Output: Mr red has a red house and a red car

Like described here: http://www.w3schools.com/jsref/jsref_replace.asp

But what you may actually wanted:

var str = "Test[separator[, limit]]Test"; 
var res = str.split("[separator[, limit]]").join(" ");
//Output: Test Test
Sander
  • 171
  • 1
  • 10