Christopher Cooper
Christopher Cooper

Reputation: 1920

Efficient way to find a string between two other strings via Javascript

This ought to be pretty simple, maybe use a regex but I would think there is an easier - faster way. Currently I make this work by using a couple of splits, but that sure seems like a poor method.

Example string:

on Jun 09, 2009. Tagged:

What I need to do is turn that date (June 09, 2009) into three strings (Jun, 09, 2009). Obviously this date may vary to things like May 25, 2011. I assume using the two outside strings which would be consistent ("on " and ". Tagged") and searching based on them is the best method. The month will always be three letters.

What would be a better way to do this via Javascript?

Thanks!

Upvotes: 1

Views: 6054

Answers (3)

Jon McIntosh
Jon McIntosh

Reputation:

You could search the string using search/slice... It's not as efficient as RegEx.

<script type="text/javascript">
  function sBs(ss1,ss2,fs) {
    ss1 = fs.search(ss1) + ss1.length; // continue *after* the first substring
    ss2 = fs.search(ss2); //grab the position of the beginning of substring2
    var sbsResult = fs.slice(ss1,ss2); 
    alert(sbsResult);
}
</script>
<a href="#" onClick="sBs('a','b','a b c');">get substring!</a>

Upvotes: 2

Chris Thompson
Chris Thompson

Reputation: 16871

You could do it using substring commands, but a regex would be simpler and less prone to breaking if the source data ever changed.

You can use this regex:

 var input = "on Jun 09, 2009 Tagged:";
 var date = input.match(/([a-zA-Z]{3}) (\d{1,2}), (\d{4})/);
 // date = ["Jun 09, 2009", "Jun", "09", "2009"];
 var simpledate = date.slice(1);
 // simpledate = ["Jun", "09", "2009"];

When using RegEx's, I find this site to be extremely useful: http://www.regular-expressions.info/javascriptexample.html

It provides a JavaScript regex tester that's very handy! You can plug in same data and a regex and run it and see the matched data. It's helped me to understand regular expressions a lot better. For example, you can see that my regex and the other answers are different but accomplish the same thing.

Upvotes: 3

Gumbo
Gumbo

Reputation: 655489

You could use a regular expression:

var match = str.match(/on (\w+) (\d{2}), (\d{4})\. Tagged/);
// match = ["on Jun 09, 2009. Tagged", "Jun", "09", "2009"]

Upvotes: 4

Related Questions