2015-02-06 113 views
-2

以下是我正在尝试完成的内容...切片长字符串

○取一个长字符串并将该字符串的每个单词推送到数组中。 - 注意:我在ITSM工具中使用此代码,因此,一旦我能够将此字符串分解为不同的值,我将使用每个值运行查询。我在这里回顾了其他一些帖子,这里是我迄今得到的代码。我知道它还没有完成代码,但这就是为什么我在这里...

var text = "This is a very long string that could be split up into different words and different variables"; 
var box = []; 
var start = 0; 
var index = 0; 

console.log(chopper(text)); 

function chopper(string){ 
    var length = string.length; 
    string = string.replace(/ /g,','); 

    for(i=0; i < length; i++){ 
     index = string.indexOf(',', start); 
       console.log("Start : " + start); 
       console.log("Index : " + index); 
     var word = string.slice(start,index); 
       string = string.substr(start,length); 
       console.log("String : " + string); 
       start = index; 
     box.push(word); 
    } 
    return box; 
} 
+2

这是你想要的吗? 'text.split('').join(',');' – Lewis 2015-02-06 14:09:41

+1

'string.split(“”);' – 2015-02-06 14:09:55

+0

有什么问题有什么问题?为什么不使用'str.split('');'来创建数组? – Andy 2015-02-06 14:10:01

回答

0

为什么不只是分割字符串?

box=text.split(new RegExp("\\s+")); 
+1

你可能意指'box = text.split(/ \ s + /);'。 – qtgye 2015-02-06 14:11:52

+0

@JaysonBuquia我的坏..谢谢.. ;-) – Anirudha 2015-02-06 14:12:50

1

为了使单词的列表从字符串(其中,“字”是拉丁语字母的序列)中,由正则表达式/[^a-z]+/i,意思是“不是字母”分裂。这将删除空格,标点符号和其他非单词内容。

var text = "This is a very long string, that could be split up: into different words and different variables"; 
 

 
words = text.split(/[^a-z]+/i) 
 
alert(words)

0

这是非常困难的尝试找出你在做什么,但这里是我的解释。

function getBox(text) { 

    // lowercase the text so that we can dedupe the arr properly 
    text = text.toLowerCase(); 

    // split the text into an array along word boundaries 
    var arr = text.split(/\b/g); 

    // dedupe the array into unique values 
    var uniqueArray = arr.filter(function (item, pos) { return arr.indexOf(item) == pos; }); 

    // set an empty object to store our word data 
    var obj = {}; 

    // for each unique word 
    for (var i = 0, l = uniqueArray.length; i < l; i++) { 
     var word = uniqueArray[i]; 

     // use it as the basis of a new regex search 
     var myRe = new RegExp('\\b' + word + '\\b', 'g'); 
     var myArray, tmpArray; 

     // we're going to use exec to find the word in the text 
     // how many times it appears 
     while ((myArray = myRe.exec(text)) !== null) { 
      if (tmpArray !== myArray[0]) { 

       // and we're going to add the information as values 
       // to the unique key in our object: how long the word is 
       // and the index positions it is found in in the text 
       // if the key isn't already there, add it. 
       obj[word] = { length: word.length, positions: [myArray.index]}; 
      } else { 

       // otherwise push the new found location into the array 
       obj[word].positions.push(myArray.index); 
      } 
      tmpArray = myArray[0]; 
     } 
    } 
    return obj; 
} 

getBox(text); 

所以你最终识别每个单词,它的长度,含在那里你会发现它在文本中的每一个索引数组中的对象。

DEMO