var mainvalue="This is first sentence. This is 2nd sentence. This is 3rd sentence.";
var matchwith="This is first";
Now I want to obtain the text in variable ‘mainvalue’ that occurs after the value stored in variable matchwith…. It is assumed here that the value in ‘matchwith’ is present in mainvalue.
Another question that I have…What if the value in ‘matchwith’ is stored more than once in mainvalue?
i.e.
var mainvalue=”This is first sentence. This is 2nd. Repeat of This is first sentence. Yet another sentence”;
Now, I want to obtain the text in ‘mainvalue’ that occurs before the last occurence of ‘This is first sentence’.
Also, I want to obtain the text in ‘mainvalue’ that occurs after the first occurence of ‘This is first sentence’
How do I do this?
Finally, how do I determine of the value “This is first sentence” occurs at beginning of mainvalue variable or not? Again, how do I find out if this value occurs right at the end of mainvalue variable or not?
I prefer pure JS, but even use of libraries like Jquery is ok with me…
First get the position of the substring in the haystack:
Then you can get the stuff before it:
Or after:
Simple. Now, on to duplicates.
In the case you outlined, you can get the string after the first match, and then get the part of that string that is before the second match (since that one will become the first). More flexible, though, is this:
Now you can get the index of the piece you like.
To see if the string starts or ends with your search pattern, you could see if the “string before/after the match” is empty, respectively.