jQuery分隔短语值字符串

时间:2016-01-22 02:44:03

标签: jquery

所以,我有以下js:

function(data){
    var length  = (data.number.split(',').length) - 1; //Holds numbers such as "1,2,3,4,5" which gives "5".         
    var content = data.content; //Holds the phrases
    alert(content); 
        for (var i=0; i<length; i++) {
                var indi_cont = data.content[i];                    
                alert(indi_cont);                   
            };                      
        };  

此处length为5,我得到了alert(content)的5个值数组(请注意值末尾的" , ")。

`my name is,how are you,i am good,thank you,hey you,`

使用for函数,我想将每个值分开,如下所示:

my name is
how are you
i am good
thank you
hey you

但是,我得到alert(indi_cont)如下:

m
y
n
a
m

因此,看起来显示的是单个字符而不是整个短语。

如何解决此问题?

谢谢!

4 个答案:

答案 0 :(得分:1)

你应该像以下那样存储返回的字符串:

function(data){
   //var length  = (data.number.split(',').length) - 1; //gives "5" 
   var splitStr = data.content.split(',');         
   //var content = data.content; 
   //alert(content); 
   for (var i=0; i< (splitStr.length - 1 ); i++) {
       var indi_cont = splitStr[i];                    
       alert(indi_cont);                   
   }                     
} 

DEMO

答案 1 :(得分:1)

您需要将split函数的返回值存储在数组中,而不是它的长度。

尝试:

function(data){
    var dataArray = data.split(',');
    for (var i=0; i<dataArray.length; i++) {
        var indi_cont = dataArray[i];                    
        console.log(indi_cont);                   
    };                      
};

小提琴: https://jsfiddle.net/bz9h95ox/

答案 2 :(得分:1)

尝试在RegExp使用/,|\s/ .split()将逗号字符","" "空格字符Array.prototype.filter()的输入文本与参数{分开{1}}从Boolean

的结果中删除空" "

.split()
var data = "my name is,how are you,i am good,thank you,hey you,";

var content = data.split(/,|\s/).filter(Boolean);

console.log(content)

for (var i = 0; i < content.length; i++) {
  document.body.innerHTML += content[i] + "<br>"
}

或者,使用<body> </body>.match() RegExp匹配字母数字字符,否定逗号字符/[a-z0-9]+[^,\s]/ig或空格","字符

" "
var data = "my name is,how are you,i am good,thank you,hey you,";

var content = data.match(/[a-z0-9]+[^,\s]/ig);

console.log(content)

for (var i = 0; i < content.length; i++) {
  document.body.innerHTML += content[i] + "<br>"
}

答案 3 :(得分:1)

我会这样做:

function(data){
    var values = data.content.split(',');
    $.each(values, function (i, value) {
        if (value.length > 0)
            console.log(value);
    });                   
};