开发者

JavaScript equivalent of the MySQL function SUBSTRING_INDEX()

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

Is there a开发者_JAVA百科ny equivalent function in JavaScript? I need to perform the same thing.. but on a string value in JavaScript.


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


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));


An old question I know, but just for the record and in case it helps anyone, the following is a slight updated to the selected answer which allows substring_index to work exactly as it does in MySQL i.e. also allowing for negative indexes.

function substring_index( input, delimiter, index ) {
    var arr = input.split( delimiter );
    if( index < 0 ){
       index = arr.length + index;
       arr.splice( 0, index );
    }else{
       arr.splice( index, arr.length - index );
    }
       return arr.join( delimiter );
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜