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
6 Answers
Reset to default 11First, 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
版权声明:本文标题:javascript - append single quotes to characters - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742334311a2455318.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论