简体   繁体   English

如何在之间添加空格

[英]How do I add spaces between

I have a page like this: 我有一个这样的页面:

屏幕截图

I want to add a set of numbers (not strings) when I press the button "set number list", but those numbers have to have spaces between them. 当我按下“设置数字列表”按钮时,我想添加一组数字(而不是字符串),但是这些数字之间必须有空格。 I have all the HTML stuff I need, but I can't seem to figure out this JavaScript part. 我拥有所需的所有HTML内容,但似乎无法弄清楚JavaScript的这一部分。 I know I can add numbers like this: 我知道我可以添加这样的数字:

document.getElementById("listNumberButton").value = 1234;

and the result will show in the box when I click the button but I have done so much searching I can't seem to figure out how to add numbers with spaces between them like this: 当我单击按钮时,结果将显示在框中,但是我做了很多搜索,似乎无法弄清楚如何在数字之间加空格,如下所示:

1 2 3 4

Convert the number to string, split it on '' , and join it with space - ie 将数字转换为字符串,在''上分割,然后将其与空格连接-即

var number = 1234;
var spacedNumber = number.toString().split('').join(' ');

or, in your case 或者,就您而言

document.getElementById("listNumberButton").value = 1234..toString().split('').join(' ');

note the .. due to Numbers having a decimal point :p 注意..因为数字有小数点:p

Try this code: works well 尝试以下代码:效果很好

 var number="1234";
 number=number.replace(/[^\dA-Z]/g, '').replace(/(.{1})/g, '$1 ').trim();
 answer will be 1 2 3 4

Run this snippet and check: 运行此代码段并检查:

 <!DOCTYPE html> <html> <head> <title>Page Title</title> <script> function myFunction() { var number=document.getElementById("split").value; number=number.replace(/[^\\dA-Z]/g, '').replace(/(.{1})/g, '$1 ').trim(); document.getElementById("result").innerHTML=number; } </script> </head> <body> <input type="text" id="split" onkeyup="myFunction()"> <h1 id="result"></h1> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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