我有一个带有文本字段的表单,用于填写网站的用户。用户通常不会在逗号和句号后添加空格。如何使用 javascript 格式化此文本区域,以便在这些逗号和句号字符后添加空格,但保留这些字符,表示数字的小数分隔符。我尝试过 replace(/\,/g,', ')
但这也在数字的小数分隔符后面放置了空格。
谢谢
最佳答案
这是使用 split 的非正则表达式解决方案:
function fixString(inp){
var i, len, arr, outp, Rside, Lside, RsideIsNum, LsideIsNum;
arr = inp.split(",");
outp = "";
for(i=1, len=arr.length; i<len; i++){
Lside = arr[i-1];
Rside = arr[i];
LsideIsNum = /\d/.test(Lside.charAt(Lside.length-1));
RsideIsNum = /\d/.test(Rside.charAt(0));
outp += "," + ((LsideIsNum && RsideIsNum)?"":" ") + Rside;
}
return (arr[0] + outp).replace(/\s\s+/g," ");
}
然后使用它只需调用 fixString(my_string)
如下:
var str_old = "a,1b,c,d2,e,3f4,g, this is a test, 1,000 yay!,2,000,ok?";
var str_new = fixString(str_old);
//str_old: a,1b,c,d2,e,3f4,g, this is a test, 1,000 yay!,2,000,ok?
//str_new: a, 1b, c, d2, e, 3f4, g, this is a test, 1,000 yay!, 2,000, ok?
但是,正如我在评论中所说,当有人说“我的幸运数字是 5 只猫中的 7,4 发出咕噜声”时,您会得到意想不到的结果
。
关于javascript - 在逗号和句号后添加空格,但如果它是小数分隔符则不添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20430587/