[英]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). JS Fiddle演示 (请打开您的JavaScript /开发人员控制台以查看输出)。
For multiple-digits: 对于多位数:
var newString = test.replace(/(\d+)/g, "'$1'");
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. 如果你需要保留逗号,请事先使用
test.split(',')
并在之后添加。 (Further explanation upon request if that's not clear). (根据要求进一步解释,如果不清楚)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.