views:

39

answers:

2

Hi,

SUBSTRING_INDEX() in MySQL returns a substring from a string before the specified number of occurrences of the delimiter.

Is there any equivalent function in JavaScript? I need to perform the same thing.. but on a string value in JavaScript.

A: 

indexOf may be what you are after: http://www.w3schools.com/jsref/jsref_IndexOf.asp

Of course, you'd have to combine this with something like substr: http://www.w3schools.com/jsref/jsref_substr.asp

EDIT: The more I looked into this, the more difficult it got to give something exactly like what you are looking for. One way to do this is with a Regular Expression, or, I wrote a simple little function that will let you use syntax nearly identical to SUBSTRING_INDEX()

function substringIndex(str, char, occurrence){
    var newStr = '';
    var occurrenceMatches = 0;

    for (var i=0; str.length; i++){
        if (str.charAt(i)==char) occurrenceMatches++;
        if (occurrenceMatches==occurrence) break;
        newStr += str.charAt(i);
    }

    return newStr;
}
alert(substringIndex('www.mysql.com', '.', 2));
Bart
@Bart: What about my split, splice, join method? It looks equivalent to the MySQL function, and a bit more terse than the for loop method you suggest.
Daniel Vassallo
Agreed. Your example is more pretty.
Bart
+5  A: 

MySQL:

SELECT SUBSTRING_INDEX('www.stackoverflow.com', '.', 1) result;
+--------+
| result |
+--------+
| www    |
+--------+
1 row in set (0.00 sec)

SELECT SUBSTRING_INDEX('www.stackoverflow.com', '.', 2) result;
+-------------------+
| result            |
+-------------------+
| www.stackoverflow |
+-------------------+
1 row in set (0.00 sec)

JavaScript:

function substringIndex (input, delimiter, index) {
  var arr = input.split(delimiter);
  arr.splice(index, arr.length - index);
  return arr.join(delimiter);
}

console.log(substringIndex('www.stackoverflow.com', '.', 1)); 
// www

console.log(substringIndex('www.stackoverflow.com', '.', 2)); 
// www.stackoverflow
Daniel Vassallo
nice.. n thanks.. :)
Nauman Bashir