1

I am trying to grab a certain value. I am new to javascript and I can't figure out why this is not working.

If I parse "kid_2" I should get "kostas". Instead of "Kostas" I always get "02-23-2000". So I must have a logic problem in the loop but I am really stuck.

function getold_val(fieldname,str){

  var chunks=str.split("||");
  var allchunks = chunks.length-1;
     for(k=0;k<allchunks;k++){
       var n=str.indexOf(fieldname);
       alert(chunks[k]);
       if(n>0){
       var chunkd=chunks[k].split("::");
         alert(chunkd);
         return chunkd[1];
       }
     }
}
var test = getold_val('kid_2','date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||');

alert(test);
4
  • It should be allchunks = chunks.length not allchunks = chunks.length-1 Commented Sep 26, 2012 at 17:10
  • 1
    Also, it should be if(n>=0) because if the key is found it really is at position 0. Commented Sep 26, 2012 at 17:13
  • In that case it shouldn't be returning anything. Commented Sep 26, 2012 at 17:16
  • I have tried all of these.. check this it may help you. jsbin.com/efajug/3/edit. Problem is that it is stucked in the first split, so the loop is not working right. Commented Sep 26, 2012 at 17:17

3 Answers 3

2

A regex may be a little more appealing. Here's a fiddle:

function getValue(source, key){
    return (new RegExp("(^|\\|)" + key + "::([^$\\|]+)", "i").exec(source) || {})[2];
}    
getValue("date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||","kid_2");

But if you want something a little more involved, you can parse that string into a dictionary like so (fiddle):

function splitToDictionary(val, fieldDelimiter, valueDelimiter){
    var dict = {},
    fields = val.split(fieldDelimiter),
    kvp;
    for (var i = 0; i < fields.length; i++) {        
        if (fields[i] !== "") {
            kvp = fields[i].split(valueDelimiter);        
            dict[kvp[0]] = kvp[1];
        }
    }
    return dict;    
}
var dict = splitToDictionary("date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||","||","::");
console.log(dict["date_1"]);
console.log(dict["date_2"]);
console.log(dict["kid_1"]);
console.log(dict["kid_2"]);​
Sign up to request clarification or add additional context in comments.

1 Comment

I am a newbie in Jscript so regular expressions - as you can imagine - was too advanced. I really thank you both suggestions work perfect.
2

This works, here's my fiddle.

function getold_val(fieldname,str) {
    var chunks = str.split('||');
    for(var i = 0; i < chunks.length-1; i++) {
        if(chunks[i].indexOf(fieldname) >= 0) {
            return(chunks[i].substring(fieldname.length+2));
        }
    }
}
alert(getold_val('kid_2', 'date_1::02-23-2000||date_2::06-06-1990||kid_1::George||kid_2::Kostas||'));

The issue with your code was (as @slebetman noticed as well) the fact that a string index can be 0 because it starts exactly in the first letter.

The code is almost the same as yours, I just didn't use the second .split('::') because I felt a .substring(...) would be easier.

7 Comments

my god you're very fast. Let me check it one moment please.
Actually, the main problem was that he was doing str.indexOf() instead of chunks[i].indexOf(). So while looking at the first chunk, it would find the fieldname in a different chunk.
Actually, using indexOf is also a bug. Should simply split everything into an array of arrays (or array of objects) and simply check if key = fieldname. This will break on kid_10 and above.
your code works great but I had to add "+2" to get ride of the dots. return(chunks[i].substring(fieldname.length+2)); I'll keep searching how to do it with the "::" as a seperator. @Barman I think you saw exactly the problem. I'll test it in a minute.
I figured it out by adding lots of console.log statements. When I logged n it said it was something like 65!
|
2

There are two bugs. The first error is in the indexOf call:

var n = str.indexOf(fieldname);

This will always return a value greater than or equal to 0 since the field exists in the string. What you should be doing is:

var n = chunks[k].indexOf(fieldname);

The second error is in your if statement. It should be:

if(n >= 0) {
   ...
}

or

if(n > -1) {
    ...
}

The substring you are looking for could very well be the at the beginning of the string, in which case its index is 0. indexOf returns -1 if it cannot find what you're looking for.

That being said, here's a better way to do what you're trying to do:

function getold_val(fieldName, str) {
    var keyValuePairs = str.split("||");
    var returnValue = null;

    if(/||$/.match(str)) {
       keyValuePairs = keyValuePairs.slice(0, keyValuePairs.length - 1);
    }

    var found = false;
    var i = 0;
    while(i < keyValuePairs.length && !found) {
       var keyValuePair = keyValuePairs[i].split("::");

       var key = keyValuePair[0];
       var value = keyValuePair[1];

       if(fieldName === key) {
          returnValue = value;
          found = true;
       }

       i++;
    }

    return returnValue;
}

8 Comments

Mihai, good point - my mistake; I didn't see the || at the end.
@VivinPaliath That return looks correct though. It is only executed if the key matches.
I really think the real bug is the if statement.
Don't use indexOf. Do chunks[k].split('::')[0] = fieldname. Think what will happen with kid_10
No, think about if kid_10 exists and kid_1 is passed in.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.