String (double quote) formatting in Javascript

I have a string

var st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv_jkl4_100x104"

Now I want to put a double quote around each substring

i.e required string

var st = ""asv_abc1_100x101", "asv_def2_100x102", "asv_ghi1_100x103", "asv_jkl4_100x104""

Is this possible to achieve anything like this in javascript?

>Solution :

If you meant to transform a string containing "words" separated by comma in a string with those same "words" wrapped by double quotes you might for example split the original string using .split(',') and than loop through the resulting array to compose the output string wrapping each item between quotes:

function transform(value){
  const words = value.split(',');
  let output = '';
  for(word of words){
    output += `"${word.trim()}", `;
  }
  output = output.slice(0, -2); 
  
  return output;
}

const st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv_jkl4_100x104";
const output = transform(st);
console.log(output);

That’s true unless you just meant to define a string literal containing a character that just needed to be escaped. In that case you had several ways like using single quotes for the string literal or backticks (but that’s more suitable for template strings). Or just escape the \" inside your value if you are wrapping the literal with double quotes.

Leave a Reply