简体   繁体   中英

How to split specific string by delimiter

i am having problems with splitting string with this name inside: Aix-en-Provence

String possibilities are:

Aix-en-Provence-Test2 Test2-Aix-en-Provence

I would like to split string dynamically with delmiter ('-') to get Aix-en-Provence and Test2 seperated.

How to? I was trying with Regex.execute with different patterns but unsuccessful. I am parsing data in Javascript.

Thanks in advance.

Best regards

You can try something like this:

function mySplit(myString, splitString, protectString){
    var specialString = 'somespecialchar';
    var r = new RegExp('(^|-)('+protectString+')(-|$)');
    var a = myString.replace(r, '$1'+specialString+'$3').split('-');
    a.forEach(function(e, i, a){
        if (e == specialString) a[i] = protectString;
    });
    return a;
}
mySplit('Aix-en-Provence-Test2', '-', 'Aix-en-Provence');
mySplit('Test2-Aix-en-Provence', '-', 'Aix-en-Provence');

The function is far from perfect, you should escape regex special chars from "protectString" but it does the job for your strings.

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