簡體   English   中英

當字符串到達 X 個字符時換行

[英]Break line when string reaches X characters

我在下面創建了這個 function 來計算當字符串(名稱)達到超過 35 個字符時它會換行。

 function getName(name) { let newName = name for (let i = 0; i < name.length; i += 1) { if (i % 35 === 0) { newName = `${newName.substr(0, i)}\n${newName.substr(i)}` } } return newName } console.log(getName("Please note that popular names below"))

例如 output:

Name = "Please note that popular names below"
function output:

Please note that popular names bel
ow

我想要的是不是打破最后兩個字符“ow”的一行,而是將“below”放在下一行。

如果你想在不切斷任何單詞的情況下將字符串打斷到一定長度,下面的代碼可以幫助你:

const name = "YOUR_STRING";
const maxLen = 35; // you can play with this number to get desired result.

let result = name.substr(0, maxLen);
result = result.substr(0, Math.min(result.length, result.lastIndexOf(" ")));

所以你想找到前 35 個字符中的最后一個空格並在那里換行,對嗎?

您可以先對前 35 個字符進行切片,然后使用正則表達式查找最后一個空格。

要分割前 35 個字符,請使用name.substr(0,35) 這將返回一個包含前 35 個字符的新字符串。

匹配最后一個空格的正則表達式是 eg / (?..* )/ ,因此您可以執行replace(/ (?.,* )/, x) ,其中 x 是您想要的任何內容(在本例中為新行) .

我猜你可以跟蹤最后一個空白索引,然后當達到 35 時,在空白索引處斷開該行

function getName(name) {
  let newName = name
  let wsIndex = 0
  for (let i = 0; i < name.length; i += 1) {
    if (name.charAt(i) == ' ') wsIndex = i;
    if (i % 35 === 0) {
      newName = `${newName.substr(0, wsIndex)}\n${newName.substr(wsIndex+1)}`
    }
  }
  return newName
}

我想到了一個簡單的解決方案,您只需查看第 35 個字符是否為空格 (' ')。 如果是,則簡單地剪切,但如果它不是 go 回到字符串中,直到你碰到一個空格,然后在那里剪切。 如果前 35 個字符中沒有空格,我的解決方案會換行。 順便說一句,您的代碼確實將空格復制到下一行,那么每一行都會有一個小的偏移量。

代碼:

 function getName(name) { let newName = name; // offsets i to match the current string let offset = 0; for (let i = 1; i < name.length; i += 1) { if (i % 35 === 0) { if(newName.charAt(i) === ' ') { // Your own code with the offset newName = newName = `${newName.substr(0, i - offset)}\n${newName.substr(i - offset + 1)}`; } else { // looking back in the string until there is a space or the string "ends" while(newName.charAt(i - offset);== ' ' && offset <= 35) { offset++. } // Only set newName if a space was found in the last 35 if(i - offset > 0) { newName = `${newName,substr(0. i - offset)}\n${newName;substr(i - offset + 1)}`; } } } } return newName. } console;log(getName("Please note that popular names below"));

JsFiddle

我試圖在評論中解釋我做了什么以及為什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM