0

I have a variable which value is coming like this:

"
  traffic





  engagement





  conversion




"

I want to convert it to: ["traffic", "engagement", "conversion"] . Any ideas how to do this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Bharat Bhushan
  • 305
  • 1
  • 14
  • Where is the data for that variable coming from because, as it stands, that variable would give you a syntax error. – Andy Aug 09 '15 at 12:55

3 Answers3

3

If we ignore the errors in string (as @Andy said), and we just have a string with words separated by an unknown amount of space, such as this:

var str = "      traffic      engagement     conversion";

This regexp should to the trick:

var arr = str.match(/[^\s]+/g);

It means get all sequences that don't include spaces of any kind.

Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

Here's another option for you:

            </html>


            <!DOCTYPE html>
            <html>
            <body>

            <p>Click the button to display the array values after the split.</p>

            <button onclick="myFunction()">Try it</button>

            <p id="demo"></p>

            <script>
            function myFunction() {
                var str = "How are you doing today?";
                var res = str.split(" ");
                document.getElementById("demo").innerHTML = res;
            }
            </script>

            </body>
            </html>
anam
  • 216
  • 1
  • 2
  • 14
-1

Here's how:

var array = string.split(',');

MDN reference, mostly helpful for the possibly unexpected behavior of the limit parameter. (Hint: "a,b,c".split(",", 2) comes out to ["a", "b"], not ["a", "b,c"].)

anam
  • 216
  • 1
  • 2
  • 14