0

I have a number of strings concatenated together

"[thing 1,thing 2,cat in the hat,Dr. Suese]"

I would like to traverse this string to stop at a specific comma (given an index) and return the substring immediately after the comma and before the next comma. The problem is I need to do it in JavaScript. I assume it would be something like this

function returnSubstring(i,theString){
    var j,k = 0;
    while(theString.charCodeAt(k) != ','){
        while(i > 0){
            if (theString.charCodeAt(j) == ','){
                i--;
            }
            j++;
        }
        k++;
    }
    return theString.substring(j,k);
}

Is this what it should look like or is there some syntax issue here

2
  • 2
    Can your data only come in this format? Why not use JSON to serialize the data? Commented Jan 13, 2014 at 14:16
  • Do you mean the index of the comma among commas (i.e. the second comma) or the index of the comma in the string (i.e the first comma after the twentieth char) ? Commented Jan 13, 2014 at 14:22

2 Answers 2

2

I would like to traverse this string to stop at a specific comma (given an index) and return the substring immediately after the comma and before the next comma.

--> Let's assume specific index for comma accpeted is 8 i.e. first comma index, you can do :

var givenCommaIndex = 8;
var value = "[thing 1,thing 2,cat in the hat,Dr. Suese]";
var subString = value.substring(givenCommaIndex+1, value.indexOf(",", givenCommaIndex+1));
console.log(subString);

// Output :
"thing 2"

I can write the reusable function like below, it will not just work for comma but other delimiters as well :

function getSubString(str, delimiter, indexOfDelimiter) {
    // TODO : handle specific cases like str is undefined or delimiter is null
    return str.substring(indexOfDelimiter+1, str.indexOf(delimiter, indexOfDelimiter+1));
}
Sign up to request clarification or add additional context in comments.

Comments

2

You may split :

var token = "[thing 1,thing 2,cat in the hat,Dr. Suese]"
    .slice(1,-1) // remove [ and ]
    .split(',')
    [2]; // the third token

Or use a regular expression :

var token = "[thing 1,thing 2,cat in the hat,Dr. Suese]"
    .match(/([^\]\[,]+)/g)
    [2];

3 Comments

He wants to input the index of the comma.
@thefourtheye This isn't clear for me. I added a question in comment.
@thefoureye my bad. one off mistake. (j+1,j+k-1) i think

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.