javascript - append single quotes to characters - Stack Overflow

I have a string like var test = "1,2,3,4";I need to append single quotes (' ') to a

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).

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742334311a4424343.html

相关推荐

  • javascript - append single quotes to characters - Stack Overflow

    I have a string like var test = "1,2,3,4";I need to append single quotes (' ') to a

    7小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信