get string between two strings with javascript [duplicate]

六眼飞鱼酱① 提交于 2021-02-15 10:41:44

问题


How do I get a string between two strings using match with variables? The following code works well if I use match with strings Regular Expression to get a string between two strings in Javascript I also tried to apply the info at JavaScript - Use variable in string match :

var test = "My cow always gives milk";

var testRE = test.match("cow(.*)milk");
alert(testRE[1]);

But what if I have:

var firstvariable = "cow";
var secondvariable = "milk";

var test = "My cow always gives milk";

I've tried various things including:

var testRE = test.match("firstvariable(.*)secondvariable");
alert(testRE[1]);

and:

var testRE = testRE.match + '("' + firstvariable + "(.*)" + secondvariable +'")';
alert(testRE[1]);

Neither worked.


回答1:


Try this:

test.match(new RegExp(firstvariable + "(.*)" + secondvariable));



回答2:


Use this code

var regExString = new RegExp("(?:"+firstvariable+")((.[\\s\\S]*))(?:"+secondvariable+")", "ig"); //set ig flag for global search and case insensitive

var testRE = regExString.exec("My cow always gives milk.");
if (testRE && testRE.length > 1) //RegEx has found something and has more than one entry.
{  
    alert(testRE[1]); //is the matched group if found
}

This matches only the middle part of the sentence.

  1. (?:"+firstvariable+") finds but does not capture cow.
  2. (.*?) captures all characters between cow and milk and saves it in a group. ? makes it lazy so it stops at milk.
  3. (?:"+secondvariable+") finds but does not capture milk.

You can test this below:

function testString()
{
    var test = document.getElementById("testStringDiv").textContent;
    var firstvariable = document.querySelectorAll("input")[0].value; //first input;
    var secondvariable = document.querySelectorAll("input")[1].value; //second input;
    var regExString = new RegExp("(?:"+firstvariable+")((.[\\s\\S]*))(?:"+secondvariable+")", "ig");
    var testRE = regExString.exec(test);

    if (testRE && testRE.length > 1)
    {  
      document.getElementById("showcase").textContent = testRE[1]; //return second result.
    }
}
document.getElementById("test").addEventListener("click", testString, true);
<div id="testStringDiv">My cow always gives milk.</div>
<div id="showcase">Result will display here...</div>
<input placeholder="enter first var"/><input placeholder="enter second var"/><button id="test">Search in between...</button>


来源:https://stackoverflow.com/questions/27656575/get-string-between-two-strings-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!