1

I want to print a string in following manner 'abc',21,'email' in javascript how can I do. below is my code.

var data = [];
data.push('abc');
data.push(21);    
data.push('email');

3 Answers 3

2

Write a function to quote a string:

function quote(s) {
  return typeof s === 'string' ? "'"+s+"'" : s;
}

Now map your array and paste the elements together with a comma:

data . map(quote) . join(',')

Since joining with a comma is the default way to convert an array into a string, you might be able to get away without the join in some situations:

alert (data . map(quote));

since alert converts its parameter into a string. Same with

element.textContent = data . map(quote);
Sign up to request clarification or add additional context in comments.

Comments

1

if data is an array defined as

var data = [];
data.push('abc');
data.push(21);    
data.push('email');

the use join() method of array to join (concatenate) the values by specifying the separator

try

alert( "'" + data.join("','") + "'" );

or

console.log( "'" + data.join("','") + "'" );

or simply

var value =  "'" + data.join("','") + "'" ;
document.body.innerHTML += value;

2 Comments

Won't that put quotes around the 21?
@torazaburo yes it will, my bad, i missed this specific detail.
-1

Now data = ['abc', 21, 'email'];

So we can use forEach function

var myString = '';

data.forEach(function(value, index){
   myString += typeof value === 'string' ? "'" + value + "'" : value;
   if(index < data.length - 1) myString += ', ';
});

console.log(myString)

Shorter version:

myString = data.map(function(value){
   return typeof value === 'string' ? "'" + value + "'" : value;
}).join(', ');

console.log(myString);

JSFiddle: https://jsfiddle.net/LeoAref/ea5fa3de/

8 Comments

You should use prv instead of using an external variable myString. Also, won't this put an extra comma at the end?
That's interesting to know why I got a negative?!
Since you're not mapping, you could just use forEach.
Ok now I use forEach, by the way, 'forEach` is more convenient, but both are the same!!!
Well, some people downvote answers if they're wrong. Anyway, you were actually on the right track with the use of reduce as you were doing before the edit. Instead of you having to declare your own variable (myString), reduce maintains this variable internally, passing it to the callback on each iteration of the loop as the first parameter, what you were calling prv.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.