使用JQuery拆分 - 循环遍历String

时间:2017-09-02 11:00:41

标签: jquery loops

我有一个字符串如下

var str = "foobar~~some example text~~this is a string, foobar1~~some example 
text1~~this is a string1";

我需要遍历此字符串并获取文本"一些示例文本","一些示例text1"

任何人都可以告诉我如何循环使用它。

4 个答案:

答案 0 :(得分:2)

您可以将.match()与以下正则表达式一起使用:

/~~[^~]+~~/g

为了循环,你可以在结果数组上使用.forEach()

reatVal.forEach(function(ele, idx) {
    console.log('element n.: ' + idx + ' value: ' + ele)
})



var str = "foobar~~some example text~~this is a string, foobar1~~some example text1~~this is a string1";
var retVal = str.match(/~~[^~]+~~/g).map(function(ele, idx) {
    return ele.replace(/~~/g, '');
});


console.log('retVal is the following array: ' + retVal);

retVal.forEach(function(ele, idx) {
    console.log('element n.: ' + idx + ' value: ' + ele)
})




答案 1 :(得分:0)

我建议使用捕获组和一些辅助方法:



String.prototype.getCapturingGroups = function(re){
  if(re instanceof RegExp){
    let groups_contents = [];
    this.replace(re, function(str, match){
      groups_contents.push(match);
    });
    return groups_contents;
  }
  return [];
}

var str = "foobar~~some example text~~this is a string, foobar1~~some example text1~~this is a string1";
var regex = /\~\~([^~]+)\~\~/g;
var content_arr = str.getCapturingGroups(regex);

content_arr.forEach((e,i)=>console.log(`n°${i} is : ${e}`))




答案 2 :(得分:0)

我试过这个并完成了它。

var arr = str.split(',');
    for (var i = 0; i < arr.length; i++) {
        var onetext = arr[i];
        var twotext = onetext.split('~~');
        for (var j =0; j< twotext.length; j++) {
            console.log(twotext[j]);
        }
    }

感谢您的快速回复。

答案 3 :(得分:0)

    var str = "foobar~~some example text~~this is a string, 
foobar1~~some example text1~~this is a string1";
    var strArr = str.split(',');
    var finalStrArr = []; 
    for(var i=0; i<strArr.length; i++) { 
        var finalStr = strArr[i].split('~~'); 
        finalStrArr.push(finalStr[1]); 
    };

仅当字符串仅以该格式出现时,此代码才有效。我的意思是上面的代码会给你字符~~后面的第一个字符串 我把finalStrArr.push(finalStr[1]);我的索引设为1,因为我假设预期的字符串将始终位于该位置。