简体   繁体   中英

append single quotes to characters

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.

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:

A short and specific solution:

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

A more complete 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(",")

更简单

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

使用正则表达式:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM