A short and simple way is just to test the first and last characters:
var input = // whatever
var wrapped = input;
if ('"' === wrapped || !('"' === wrapped[0] && '"' === wrapped.slice(-1)))
wrapped = '"' + wrapped + '"';
(This works even on empty strings, because ''[0]
is undefined
and ''.slice(-1)
is ''
, neither of which cause a problem in the if
condition.)
You don’t say what to do if the input is just a single double-quote character, but I’ve assumed for the input '"'
the output will be '"""'
. If that’s not what you want obviously you can modify the code above.
1
solved Wrap a given input string in double quotes if not already wrapped