簡體   English   中英

將字符串分成不同的行?

[英]breaking a string into different lines?

在javascript中如果超過25個字符分成兩行,如何打破我的字符串,如果我的字符串包含75個字符我想要將字符串變為三行25個字符。

提前致謝

使用正則表達式很容易實現:

var text = '75 characters long (really!) — well... maybe not, but you get the picture.',
    broken;
broken = text.replace(/([^\0]{25})/g, '$1\n');

正如這里所示: http//jsbin.com/ajiyo/3

編輯 :解釋正則表達式:它將匹配任何字符串(除NUL之外的每個字符的集合),即25個字符長。

括號()表示應捕獲此部分,第二個參數(替換字符串)的“$ 1”部分表示第一次捕獲。

找到的每個25個字符的字符串將被'本身加上換行符'替換。 如果余數小於25個字符,則不會匹配,而是單獨保留。

第二次編輯 :Brock是對的,圓點在方括號中失去了它的特殊含義。 我用所有非NUL字符替換了它,因為我不希望文本字符串中有NUL字符。

嘗試使用這樣的東西

var point=0;

var myStr="12345678901234567890ABCDE my very long string 12345678901234567890ABCDE";
var myRes="";
while(myStr.substring(point).length>25)
{
  myRes=myRes+myStr.substring(point,point+25)+"\n"
  point+=25;
}

return myRes+myStr.substring(point);

這應該讓你非常接近:

var txt = "This is a really long string that should be broken up onto lines of 25 characters, or less.";

for (i=0;i<(Math.ceil(txt.length/25));i++) {
    document.write(txt.substring(25*i,25*(i+1)) + "<br />");
}

見工作示例:

http://jsfiddle.net/dbgDj/

在javascript中使用等效的str_split(php)

http://phpjs.org/functions/str_split:530

 function str_split (string, split_length) {
    // Convert a string to an array. If split_length is specified,
    // break the string down into chunks each split_length characters long.  
    // 
    // version: 1101.3117
    // discuss at: http://phpjs.org/functions/str_split    
    // +     original by: Martijn Wieringa
    // +     improved by: Brett Zamir (http://brett-zamir.me)
    // +     bugfixed by: Onno Marsman
    // +      revised by: Theriault
    // +        input by: Bjorn Roesbeke (http://www.bjornroesbeke.be/)    
    // +      revised by: Rafał Kukawski (http://blog.kukawski.pl/)
    // *       example 1: str_split('Hello Friend', 3);
    // *       returns 1: ['Hel', 'lo ', 'Fri', 'end']

    if (split_length === null) {
        split_length = 1;    }
    if (string === null || split_length < 1) {
        return false;
    }
    string += '';
    var chunks = [], pos = 0, len = string.length;
    while (pos < len) {
        chunks.push(string.slice(pos, pos += split_length));
    }
    return chunks;
}

暫無
暫無

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

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