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

How to return a substring between two matching substrings in JavaScript?

本文关键字:字符串 两个 之间 JavaScript 返回      更新时间:2023-09-26

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

我正在尝试在两个"蓝色"之间生成子字符串。那是:

", 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");

任何建议将不胜感激。

如果字符串可能具有 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];

这几乎就是这个想法。我可能在某些地方搞砸了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;

我自己作为 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() 而不是返回。概念类似。https://jsfiddle.net/felicedeNigris/7nuhujx6/

我希望我在侧面的长篇评论足够清楚吗?

希望这有帮助。