2017-06-15 65 views
0

我有我想分手的字符串文本。我需要通過Facebook信使聊天API發送它,但該API只允許640個字符,而我的文本要長得多。我想要一個整齊的解決方案,我可以通過它發送文本。在JavaScript中將包含多個段落的字符串分成兩部分

我是把包含多個段落的字符串拆分到最近的句號的兩半。

var str = "This is paragraph one. I need Mr. Sam to my errand. The errand must be done by him. He is the best. 

Mr. Sharma is also good. Btw this is the second paragraph. I think you get my point. Sentence again. Sentence again. 

Paragraph three is started. I am writing so much now. This is fun. Thanks"; 

//Expected output 

var half1 = "This is paragraph one. I need Mr. Sam to my errand. The errand must be done by him. He is the best. 

Mr. Sharma is also good. Btw this is the second paragraph." 

var half2 = "I think you get my point. Sentence again. Sentence again. 

Paragraph three is started. I am writing so much now. This is fun. Thanks" 
+0

所以看640字和工作方式回來... – epascarello

回答

0
var results=[]; 
var start=0; 
for(var i=640;i<str.length;i+=640){//jump to max 
while(str[i]!=="."&&i) i--;//go back to . 
    if(start===i) throw new Error("impossible str!"); 
    results.push(str.substr(start,i-start));//substr to result 
    start=i+1;//set next start 
} 
} 
//add last one 
results.push(str.substr(start)); 

你可以通過使640向前邁出一步,然後回到最後一個走過去的字符串。 ,創建一個子串並重復。

+1

什麼是在上面的代碼? –

+0

@rohan sood對不起的錯字... –

3

認爲這是一個基礎:

let slices = [], s; 
for(let i = 0; s = a.slice(i * 640, (i+1) * 640); i++) 
    slices.push(s); 

切片陣列將包含文本字符640塊。但我們希望這是空間感知。我們需要在不超過640分的情況下儘可能接近640分。如果我們想知道的空間,它會讓我們的生活更容易處理整個句子而不是字符:

// EDIT: Now, if a sentence is less than 640 chars, it will be stored as a whole in sentences 
// Otherwise, it will be stored in sequential 640-char chunks with the last chunk being up to 640 chars and containing the period. 
// This tweak also fixes the periods being stripped 
let sentences = str.match(/([^.]{0,639}\.|[^.]{0,640})/g) 

這裏是一個討厭的正則表達式的行動快速演示:https://jsfiddle.net/w6dh8x7r

現在我們可以一次創建最多640個字符的結果。

let result = '' 
sentences.forEach(sentence=> { 
    if((result + sentence).length <= 640) result += sentence; 
    else { 
     API.send(result); 
     // EDIT: realized sentence would be skipped so changed '' to sentence 
     result = sentence; 
    } 
}) 
+0

謝謝你,你是一個救世主:D –

+0

你明白了。我剛剛意識到,如果任何單個句子的長度超過640個字符,您會發現奇怪的行爲,所以請牢記這一點。 – Will

+0

那麼最後一句話呢?例如如果有1626個字符。只有第一個1280將被髮送。其他人呢? –

0
var txt = 'This is paragraph one. I need Mr. Sam to my errand. The errand must be done by him. He is the best. Mr. Sharma is also good. Btw this is the second paragraph. I think you get my point. Sentence again. Sentence again. Paragraph three is started. I am writing so much now. This is fun. Thanks' 
    var p = [] 
    splitValue(txt, index); 

    function splitValue(text) 
    { 
     var paragraphlength = 40; 
     if (text.length > paragraphlength) 
     { 
      var newtext = text.substring(0, paragraphlength); 
      p.push(newtext) 
      splitValue(text.substring(paragraphlength + 1, text.length)) 
     } 
    } 
相關問題