PDA

View Full Version : Get string from string


Coastal Web
10-24-2006, 08:04 PM
Hello everyone,
I was hoping someone would be able to help me out with a javascript.

I need a javascript function that will take will take a string, a starting point, and ending point, and return the contents of the string between "starting point" and the "ending point".

For example:
var string = "this is a test string";
var myString = GetString(string, "is", "string"); //<- function l need created.
//as a result of the 'GetString()' function myString = "a test"
//when fed through the javascript function, that l need help with.

I've attached a php script that does the same thing, however l am in need of a javascript equivalent.

Here's a PHP example of what l need the javascript to do:
<?php
function GetString($source, $start, $end) {
$startInt = strpos($source,$start) + strlen($start);
$endInt = strpos(substr($source, $startInt, strlen($source) - $startInt), $end) + $startInt;
return substr($source, $startInt, $endInt - $startInt);
}

$myString = "this is a test string";
//returns: this is a test string

$shortStrin = GetString($myString, "is", "string");
//returns: a test
?>

I hope l've explained this enough, and one of you more seasoned javascript vets will be able to help me out with this.

Samantha G.

coothead
10-24-2006, 09:17 PM
Hi there Samantha Gram,

here are two basic examples....
<script type="text/javascript">
<!--
/*example one*/
pattern='this is a test string';
substr=pattern.substring(7,14)
alert(substr);
/*example two*/
start=pattern.split(' is')[1];
substr_1=start.split('string')[0];
alert(substr_1);
//-->
</script>
...but there is probably a more elegant way of doing this. ;)

coothead

JUD
10-24-2006, 09:43 PM
Here's another


var string = 'this is a test string';
function GetString(source, start, end){
var st = source.indexOf(' ' + start);
var en = source.indexOf(end, start);
var returnString = source.substring(st, en);

alert(returnString);
}

Coastal Web
10-24-2006, 10:41 PM
Thank you very much for the quick help you guys. JUD, l was able to tweak yours to do exactly what l needed

The problem with yours, is that it was still returning the value of "start" in the string, and l just needed what is between start & end. But in any event, l wouldn't have been able to do it with out your help, thank you so much.

---
For anyone that finds/uses this thread in the future here's what l ened up with...
<script>
function trimAll(sString) {
//this is used to trim extra spaces from entry...
while (sString.substring(0,1) == ' '){
sString = sString.substring(1, sString.length);}
while (sString.substring(sString.length-1, sString.length) == ' '){
sString = sString.substring(0,sString.length-1);}
return sString;
}
function GetString(source, start, end){
var st = source.indexOf(start) + start.length;
var en = source.indexOf(end, start);
var returnString = trimAll(source.substring(st, en));
}
</script>