![](/img/trans.png)
[英]How can I insert a character after every n characters in javascript?
[英]JavaScript: Insert a character after every N characters
我有一個字符串,它的長度始終為 32:
var str = "34v188d9cefa401f988563fb153xy04b";
現在我需要在以下字符數后添加減號 (-):
Output 應該是:
34v188d9-cefa-401f-9885-63fb153xy04b
到目前為止,我已經嘗試了不同的計算,例如:
str.split('').reduce((a, b, c) => a + b + (c % 6 === 4? '-': ''), '');
但我沒有得到預期的結果。
您可以使用正則表達式替換:
var str = "34v188d9cefa401f988563fb153xy04b"; var output = str.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, "$1-$2-$3-$4-$5"); console.log(output);
如果你想使用 reduce 你可以做這樣的事情
var str = "34v188d9cefa401f988563fb153xy04b"; const result = str.split('').reduce((res, c, i) => { const hiphensPositions = [7, 11, 15, 19] return res + c + (hiphensPositions.includes(i)?'-':'') }, '') console.log(result)
var str = "34v188d9cefa401f988563fb153xy04b";
var a=""
for (let i in str){if (i == 7 || i==11 || i==15 || i ==
19){a = a+str[i]+"-"} else{a+=str[i] }}
應該這樣做。
你可以拼接它們。
const str = "34v188d9cefa401f988563fb153xy04b"; const indices = [8,12,16,20] let strArr = str.split('') indices.reverse().forEach(i => strArr.splice(i,0,'-')) console.log(strArr.join(''))
您可以使用 substring 方法
var str = '34v188d9cefa401f988563fb153xy04b'; var newStr = str.substring(0, 8) + '-' + str.substring(8, 12) + '-' + str.substring(12, 16) + '-' + str.substring(16, 20) + '-' + str.substring(20); console.log(newStr);
對於這種情況,我有一個 for 循環算法。 它需要 O(n) 的復雜性。 代碼示例是這樣的:
const str = "34v188d9cefa401f988563fb153xy04b"
let dashPosition = [8, 12, 16, 20]
for(i=arr.length-1 ; i>=0 ; i--) {
str = str.substr(0, [arr[i]]) + '-' + str.substr(arr[i])
}
答案符合你的要求嗎?
你可以用拼接和循環來做到這一點。
循環遍歷所有要添加 - 的位置,並使用索引確保每次向字符串添加新字符時,插入 - 所需的位置也會遞增。
const str = "34v188d9cefa401f988563fb153xy04b";
const positions = [8, 12, 16, 20];
const strChars = str.split("");
for(const [index, position] of positions.entries()) {
strChars.splice(position + index, 0, "-");
}
const output = strChars.join("");
console.log(output); // expected output: "34v188d9-cefa-401f-9885-63fb153xy04b"
您可以將其包裝在一個 function 中,它只采用字符串和位置數組,如下所示:
function insertHyphens(str, positions) {
const strChars = str.split("");
for(const [index, position] of positions.entries()) {
strChars.splice(position + index, 0, "-");
}
return strChars.join("");
}
console.log(insertHyphens("34v188d9cefa401f988563fb153xy04b", [8, 12, 16, 20]));
// expected output: "34v188d9-cefa-401f-9885-63fb153xy04b"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.