简体   繁体   中英

split string based on a symbol

I'm trying to split a string into an array based on the second occurrence of the symbol _

var string = "this_is_my_string";

I want to split the string after the second underscore. The string is not always the same but it always has 2 or more underscores in it. I always need it split on the second underscore.

In the example string above I would need it to be split like this.

var split = [this_is, _my_string];
var string = "this_is_my_string";
var firstUnderscore = string.indexOf('_');
var secondUnderscore = string.indexOf('_', firstUnderscore + 1);
var split = [string.substring(0, secondUnderscore),
             string.substring(secondUnderscore)];

Paste it into your browser's console to try it out. No need for a jsFiddle.

var str = "this_is_my_string";

var matches = str.match(/(.*?_.*?)(_.*)/); // MAGIC HAPPENS HERE

var firstPart = matches[1];  // this_is
var secondPart = matches[2]; // _my_string

This uses regular expressions to find the first two underscores, and captures the part up to it and the part after it. The first subexpression, (.*?_.*?) , says "any number of characters, an underscore, and again any number of characters, keeping the number of characters matched as small as possible, and capture it". The second one, (_.*) means "match an underscore, then any number of characters, as much of them as possible, and capture it". The result of the match function is an array starting with the full matched region, followed by the two captured groups.

var string = "this_is_my_string"; 
var splitChar = string.indexOf('_', string.indexOf('_') + 1);

var result = [string.substring(0, splitChar),
string.substring(splitChar, string.length)];

This should work.

I know this post is quite old... but couldn't help but notice that no one provided a working solution. Here's one that works:

    String str = "this_is_my_string";
    String undScore1 = str.split("_")[0];
    String undScore2 = str.split("_")[1];
    String bothUndScores = undScore1 + "_" + undScore2 + "_";
    String allElse = str.split(bothUndScores)[1];
    System.out.println(allElse);

This is assuming you know there will always be at least 2 underscores - "allElse" returns everything after the second occurrence.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM