SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Guru
    Join Date
    Jun 2004
    Location
    UK
    Posts
    605
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    String manipulation

    Hi,

    I have a string like this:

    Code:
    v=1|w=2|x=3|y=4|z=5
    I'd like to get the value of one of the variables given the variable name. e.g. I need to know what the value of x is.

    Here is the code I have so far:

    Code:
    //Call function
    getValue('x');
    
    function getValue(variableIn){
    	var wholeString = 'v=1|w=2|x=3|y=4|z=5';
    	if(wholeString){
    		var stringArray = wholeString.split('|');
    		for(x in stringArray) {
    			var stringItem = stringArray[x];
    			var arrayStringItem = stringItem.split('=');
    			for (y in arrayStringItem) {
    				alert(arrayStringItem[y]);
    			}
    		}
    	}else{
    		return(0);
    	}
    }
    This successfully alerts for each variable and value so I know it's almost working, but I need to just return the value of the variable passed into the function.

    Can someone show me how to do this?

    Thanks folks...

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    function getValue(variableIn){
    	var wholeString='v=1|w=2|x=3|y=4|z=5';
    	var rx= RegExp('\\b'+variableIn+' *\=([^\\|]+)');
    	return rx.exec(wholeString)[1];
    }

    getValue('x')

  3. #3
    SitePoint Guru
    Join Date
    Jun 2004
    Location
    UK
    Posts
    605
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Great, thanks for that - very neat indeed. Just one issue... I need to return the number zero if the variable being input isn't present in the string. At the moment it just errors when I call something like getValue('a');.

    Is there a similarly elegant solution to this?

    Thanks mrhoo!

  4. #4
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    function getValue(variableIn){
    	var wholeString='v=1|w=2|x=3|y=4|z=5';
    	var rx= RegExp('\\b'+variableIn+' *\=([^\\|]+)');
    	var val= rx.exec(wholeString);
    	return val? val[1]: 0;
    }


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •