PDA

View Full Version : Creating one string from another using a RegExp??


Jeepers
12-27-2002, 07:55 PM
Hi all

I need to extract one string from another. The string I want to create will always be between the same set of character, for example:

I need to create the new string of 'Hello' from the string '12345< Hello >abcde' the <+space character (‘< ‘) and space character+> (‘ >’) will always mark the beginning and end of the string that needs to be extracted, what is between the markers will always be different. By the way this has nothing to do with extracting the tag names from HTML code, I have just used those characters as an example.

I thought a regular expression may be the answer because the marker characters will always be the same, but I have absolutely no idea on how to do this.

Any help gratefully received.

jkd
12-27-2002, 08:06 PM
Pretend myString holds the raw string:

var subStrings = myString.match(/<[^>]+>/g);
for (var i = 0; i < subStrings.length; i++)
subStrings[i] = subStrings[i].substring(2, subStrings[i].length-2);

subStrings is now an array containing all the matches, stripped of the leading "< " and trailing " >".

ca_redwards
12-27-2002, 09:23 PM
In my HTML() bookmarklet library (http://www.angelfire.com/ca/redwards/html__.calendar.html), I use regular expressions to rewrite 5 functions into 154 more functions! :D

Jeepers
12-27-2002, 11:17 PM
Thanks jkd, spot on (as usual) and works a treat... :thumbsup: