我想撰寫一個函式,在給定索引的情況下,它會<br>在字串中的每個 Ith 索引處添加一個標簽。如果索引是空格,我們將插入 a <br>,但如果它在字串的中間,我們將插入-<br>
我看到了很多使用正則運算式和連接組合的示例,但我不確定如何執行此操作,因為我的連接是有條件的。
例如:
let my_string = "Here's a really really long string that I want to add breaks to at every 20th interval"
我希望我的函式 insert_break(my_string, 20) 回傳
Here's a really reall-<br>y long string that I<br> want to add breaks <br>to at every 20th interval
到目前為止,我的函式在第一個指定的索引處作業,但我不確定是否應該撰寫回圈或遞回函式以使其index在字串中的每個間隔都作業(在示例中[20,60,40],現在它只作業在20
對該功能的任何幫助表示贊賞:
insert_break = (str, index) => {
// mostly we'll need to hyphenate the new line
let breakword = "-<br>"
// but if there's a space before the index we dont
if (str[index] === " ") { breakword = "<br>" }
// I want this to run at every multiple of 20 within the string
// so I need some kind of for loop (or something recursive?)
// to add a <br> at every multiple of the index
if (index > 0) {
// this works if we only want to run this function ONCE at the index 20
//return str.substring(0, index) breakword str.substring(index)
let breakstring = str
for (let i = 1; i < Math.floor(str.length/index); i ) {
// 1*20, 2*20, 3*20
let idx = index*i
// this doesnt work.
// I need to add it to the new string, not write over the old one as I am here
breakstring = breakstring.substring(0, idx) breakword breakstring.substring(idx)
}
return breakstring
//return str.substring(0, index) breakword str.substring(index)
}
return breakword str
}
任何幫助表示贊賞!
uj5u.com熱心網友回復:
以 .的步長回圈字串索引index。用于substring()從字串中提取每個字符塊,檢查其最后一個字符,然后附加適當形式的<br>.
function insert_break(str, index) {
let result = "";
for (let i = 0; i < str.length; i = index) {
let chunk = str.substring(i, i index);
if (chunk.endsWith(' ')) {
chunk = '<br>';
} else {
chunk = '-<br>';
}
result = chunk;
}
result = result.replace(/-?<br>$/, ''); // remove last `<br>`
return result;
}
let my_string = "Here's a really really long string that I want to add breaks to at every 20th interval";
console.log(insert_break(my_string, 20));
索引從 0 開始,而不是 1,因此您需要將其用作 的初始值i。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/513165.html
上一篇:使用for回圈將串列轉換為資料框
