Ravi Kant
Ravi Kant

Reputation: 69

JavaScript with Ruby

I am using Rails 4.1.6 & Ruby 2.1.5

In Javascript I took one Variable x

var x= ravi,kant,ashish

I want to show output like below

["ravi","kant","ashish"]

I write this code

var x = ravi,kant,ashish

var z = x.map(function(p){ return '"' + p + '"'; }).join(',');

If I put alert(z); the output becomes "ravi","kant","ashish" and again if I put alert(z[0]), it should come "ravi" but its coming "(double quotes)

Please suggest me how to get the output. I want answer in JS only.

Upvotes: 0

Views: 46

Answers (1)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

You need to use split()

var str = "How are you doing today Ravi?";
var res = str.split(" "); // ["How", "are", "you", "doing", "today", "Ravi?"]
res[0] // "How"

Taking your example

var x= "ravi,kant,ashish";
y = x.split(","); // ["ravi","kant","ashish"]
y[0]; // "ravi"

http://www.w3schools.com/jsref/jsref_split.asp

Hope that helps!

Upvotes: 1

Related Questions