admin管理员组

文章数量:1336321

I have a string like

var test = "1,2,3,4";

I need to append single quotes (' ') to all characters of this string like this:

var NewString = " '1','2','3','4' ";

Please give me any suggestion.

I have a string like

var test = "1,2,3,4";

I need to append single quotes (' ') to all characters of this string like this:

var NewString = " '1','2','3','4' ";

Please give me any suggestion.

Share Improve this question edited Nov 22, 2012 at 12:33 bfavaretto 71.9k18 gold badges117 silver badges159 bronze badges asked Nov 22, 2012 at 12:31 Aarif QureshiAarif Qureshi 4741 gold badge3 silver badges13 bronze badges 1
  • 3 It seems you've already answered to your own question : test = "'1','2','3','4'";. – Teemu Commented Nov 22, 2012 at 12:34
Add a ment  | 

6 Answers 6

Reset to default 11

First, I would split the string into an array, which then makes it easier to manipulate into any form you want. Then, you can glue it back together again with whatever glue you want (in this case ','). The only remaining thing to do is ensure that it starts and ends correctly (in this case with an ').

var test = "1,2,3,4";

var formatted = "'" + test.split(',').join("','") + "'"
var newString = test.replace(/(\d)/g, "'$1'");

JS Fiddle demo (please open your JavaScript/developer console to see the output).

For multiple-digits:

var newString = test.replace(/(\d+)/g, "'$1'");

JS Fiddle demo.

References:

  • Regular expressions (at the Mozilla Developer Network).

Even simpler

test = test.replace(/\b/g, "'");

A short and specific solution:

"1,2,3,4".replace(/(\d+)/g, "'$1'")

A more plete solution which quotes any element and also handles space around the separator:

"1,2,3,4".split(/\s*,\s*/).map(function (x) { return "'" + x + "'"; }).join(",")

Using regex:

var NewString = test.replace(/(\d+)/g, "'$1'");

A string is actually like an array, so you can do something like this:

var test = "1,2,3,4";
var testOut = "";
for(var i; i<test.length; i++){
   testOut += "'" + test[i] + "'";
}

That's of course answering your question quite literally by appending to each and every character (including any mas etc.).

If you needed to keep the mas, just use test.split(',') beforehand and add it after. (Further explanation upon request if that's not clear).

本文标签: javascriptappend single quotes to charactersStack Overflow