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?
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?
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.
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>
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"].)