Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Substringing Unknown Lengths 2

Status
Not open for further replies.

TheConeHead

Programmer
Joined
Aug 14, 2002
Messages
2,106
Location
US
If I had these strings:

this changed from: aa to: bbbb by: Tom
this changed from: ddddddto: xx by: Sally
this changed from: s to: hhhhhhhhh by: Jim

And I wanted to capture the stuff right after to: - meaning in these examples I would want bbbb, xx, hhhhhhhhh - how could I do this?

[conehead]
 
Code:
var s = 'this changed from: ddddddto: xx by: Sally';
var s2 = s.substring(s.indexOf('to: ') + 4, s.indexOf(' by:'));
alert(s2);

Of course, you're probably better off using regexp, but I'm clueless about that!

Dan

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
How about
Code:
var splitter = 'to: ';
var onestring = 'this changed from: ddddddto: xx by: Sally';
var splitoff = onestring.split(splitter);
alert(splitoff[1].substr(0, splitoff[1].indexOf(' '));

or

Code:
var splitter = 'to: ';
var onestring = 'this changed from: ddddddto: xx by: Sally';
var splitoff = onestring.substr(onestring.indexOf(splitter) + splitter.length);
splitoff = splitoff.substr(0, splitoff.indexOf(' '));
alert(splitoff);

Lee
 
Here's the ultra sexy regexp solution:

Code:
<script type="text/javascript">

var a = "this changed from: aa to: bbbb by: Tom"
var b = "this changed from: ddddddto: xx by: Sally"
var c = "this changed from: s to: hhhhhhhhh by: Jim"
var d = "blahblahblahblahblahblah";

var myRegexp = new RegExp("to:(.*)by:");

var e = myRegexp.exec(a);
var f = myRegexp.exec(b);
var g = myRegexp.exec(c);
var h = myRegexp.exec(d);

alert((e == null) ? "no match found in the string" : e[1]);
alert((f == null) ? "no match found in the string" : f[1]);
alert((g == null) ? "no match found in the string" : g[1]);
alert((h == null) ? "no match found in the string" : h[1]);

</script>

or if you want it in function form:

Code:
function blah(str) {
   var a = /to:(.*)by:/.exec(str);
   return (a == null) ? false : a[1];
}

-kaht

How much you wanna make a bet I can throw a football over them mountains?
sheepico.jpg
 
kaht, that was super sexy! I played around with exec and am astonished! I keep vowing to get more familiar with regular expressions, but this cinches it! Online tutorials, here I come!

Star for the inspiration!

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
heh, thanks

-kaht

How much you wanna make a bet I can throw a football over them mountains?
sheepico.jpg
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top