Home > database >  convert string to a string Array in javascript
convert string to a string Array in javascript

Time:11-29

Sorry , please bare with me , ah I would just like to ask for the terminology and how do we implement or convert a string into something like below. I am not sure if that is string array or something but the output should look like the example.

Thanks for any help and ideas. Appreciated.

let a = 'propertyAccountId';

output = "[\"propertyAccountId\"]"

let b = 'name';
output = "[\"name\"]"

CodePudding user response:

For get the output you desire you could do this:

const b = 'name'
const output = JSON.stringify([b])

CodePudding user response:

let a = "propertyAccountId";

function convert(stringvar){
   var newstring = `["${stringvar}"]`
   return newstring;
}

console.log(convert(a));

See desired output in console here:

https://codesandbox.io/s/floral-leaf-ioxb26?file=/src/index.js:0-143

Hope this helped.

Happy coding :)

CodePudding user response:

You can turn your string input to your requested string output like below:

let a = 'propertyAccountId';
let b = 'name';
const convert = input => {
  return JSON.stringify([input]).replace(/["]/g, "\\\"")
}

console.log(convert(a))
console.log(convert(b))

  • Related