如何在JavaScript中返回两个匹配子串之间的子字符串?

时间:2014-11-30 00:28:54

标签: javascript string

我是编程的新手,刚刚开始在线课程。我被问到的问题是: 返回两个匹配子字符串之间的子字符串。 我正在使用的字符串是: “紫罗兰是蓝色的,天空真的很蓝”

我正在尝试在两个“蓝色”之间生成子串。 那就是:

", the sky is really "

这是我尝试过的一项无法解决的问题。我试图使用indexOf()lastIndexOf()对其进行切片。

module.exports.substringBetweenMatches = function(text, searchString) {

  return text.substring(function indexOf(searchString), function lastIndexOf(searchString);

};

module.exports.substringBetweenMatches("Violets are blue, the sky is really blue", "blue");

任何建议都将不胜感激。

3 个答案:

答案 0 :(得分:0)

这几乎就是这个想法。我可能在某些地方弄乱了JavaScript的语法,但逻辑是这样的:

function endsWith(a, s) {
  var does_it_match = true;
  var start_length = a.length()-s.length()-1;
  for (int i=0; i<s.length(); i++) {
    if (a[start_length+i]!=s.charAt(i)) {
        does_it_match = false;
    }
  }
  return does_it_match;
}

var buffer = new Array();
var return_string = "";
var read = false;
for (int i=0; i<string1.length(); i++) {
    buffer.push(string1.charAt(1));
    if (endsWith(buffer, "blue") && read==false) {
        buffer = new Array();
        read = true;
    }
    else if(endsWith(buffer, "blue") && read==true) {
        break;
    }
    if (read==true) {
        return_string = return_string.concat(string1.charAt(i));
    }
}

return return_string;

答案 1 :(得分:0)

如果字符串可能具有超过2个“匹配”,则可以在匹配项上拆分字符串,然后循环并将字符串连接在一起:

var array = text.split(searchString); // split the given text, on the search term/phrase

if (array.length > 2) { // check to see if there were multiple sub-sections made
    var string = ""; 
    for (var i = 1; i < array.length; i++) { // start at 1, so we don't take whatever was before the first search term
        string += array[i]; // add each piece of the array back into 1 string
    }

    return string;
}

return array[1];

答案 2 :(得分:0)

我作为Bloc.io训练营计划的学生自己偶然发现了这个问题。我坚持使用课程string.substring()方法以及string.indexOf()方法。这是我的回答。

substringBetweenMatches = function(text, searchString) { //where text is your full text string and searchString is the portion you are trying to find.
  var beginning = text.indexOf(searchString)+searchString.length; // this is the first searchString index location - the searchString length;

  var ending = text.lastIndexOf(searchString); // this is the end index position in the string where searchString is also found.

  return(text.substring(beginning,ending)); // the substring method here will cut out the text that doesn't belong based on our beginning and ending values.
};

如果您对我的代码感到困惑,请尝试:  console.log(beginning);  和 console.log(ending); 查看它们的值以及它们如何与substring()方法一起使用。

这是对substring()方法的很好的引用:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring

这是一个JS小提琴测试。我使用alert()而不是return。这个概念很相似。 https://jsfiddle.net/felicedeNigris/7nuhujx6/

我希望我对双方的长篇评论足够清楚了吗?

希望这有帮助。