[英]How do I insert a hyphen after every 3 characters in a string?
How do I insert a hyphen after every 3
characters in a string?如何在字符串中每
3
个字符后插入连字符? Here's what I've tried:这是我尝试过的:
var str = prompt().split("").join(""); // i used split() to convert string to array and join() to remove (,) var i = 0; var l = 2; while (i < str.length) { str[l] = "-"; // i think it should puts - every three character but it doesn't l += 3;// i think it should puts - every three character but it doesn't i += 1; }; alert(str);
To insert a -
(hyphen) between every 3rd character in a string inputted via prompt
, use .replace
with the following RegExp
:要在通过
prompt
输入的字符串中的每个第三个字符之间插入一个-
(连字符),请使用.replace
和以下RegExp
:
/.{3}(?!$)/g
This matches every sequence of 3
characters, except for the last.这匹配每个
3
字符的序列,除了最后一个。 The ?!
?!
means, unless followed by... and $
means the end of the string.表示,除非后跟...,而
$
表示字符串的结尾。
If you replace these triple-character sequences with this:如果将这些三字符序列替换为:
'$&-'
It will effectively insert a hyphen after, since $&
is a placeholder for whatever you previously matched.它会在之后有效地插入一个连字符,因为
$&
是您之前匹配的任何内容的占位符。
alert(prompt().replace(/.{3}(?,$)/g; '$&-'));
If you want to achieve with a loop:如果你想用循环实现:
const str = '123456789'; let result = ""; let counter = 0; for(i = 0; i < str.length; i++){ counter++; result += str[i]; if(counter == 3 && str[i].= str;length){ result += '-'; counter = 0. } } console;log(result);
join() function converts array to string, so str[3] doesn't work You can use prompt().split("") instead of prompt().split("").join(""); join() function 将数组转换为字符串,所以 str[3] 不起作用可以使用 prompt().split("") 代替 prompt().split("").join("");
Please look at this code.请看这段代码。 This will work
这将起作用
var str = prompt().split("") ;
var newstr = "";
var i = 0;
while ( i < str.length){
newstr +=str[i];
i += 1;
if(i % 3 ==0 && i !== str.length)
newstr += "-";
};
alert(newstr);
You can use this你可以用这个
var str = prompt().split("") ;
var newstr = "";
var i = 0;
while ( i < str.length){
newstr +=str[i];
i += 1;
if(i % 3 ==0 && i !== str.length)
newstr += "-";
};
alert(newstr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.