0

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?

1
  • 1
    then just put everything in single quote: var str = '"one", "two", "three"'; Commented Sep 8, 2022 at 9:13

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

for the sake of records, the @CherryDT answer was much better and mine was wasting lines doing the trim and the for loop instead of using join.
1

You can use backticks ``

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

Comments

1

You can split the string by the comma and space, map each word to a quote-wrapped version of it and then join the result again:

const result = myString
  .split(', ')
  .map(word => `"${word}"`)
  .join(', ')

Comments

0

Also you can transform your string with standard regular expressions:

// String
let st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv _ jkl4 _ 100x104";

// Use regular expressions to capture your pattern,
// which is based on comma separator or end of the line
st = st.replace(/(.+?)(,[\s+]*|$)/g, `"$1"$2`);

// Test result
console.log(st);

Comments

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.