CarlTaylor1989 CarlTaylor1989 - 1 month ago 7
Javascript Question

How to split strings based on characters either side of the character being split

I have an array of strings (example below) which is being looped and I need to be able to get the last ID and Name.

/18264:Blues (all)/19307:Acoustic Blues
/18264:Blues (all)/19308:Blues
/18267:Dance/Electronica


From the above example, I want to achieve this:

id: 19307
name: Acoustic Blues

id: 19308
name: Blues

id: 18267
name: Dance/Electronica


So it's getting the last id and name however I have issues with names that have slashes in them (IE Dance/Electronica) is there a way to ignore that slash? My code is below (example):

angular.forEach(obj, function(val, key) {
// /18264:Blues (all)/19307:Acoustic Blues
var str = key.split('/').pop();
// 19307
var id = str.split(':')[0];
// Acoustic Blues
var name = str.split(':')[1];

newObj.push({ 'id': id, 'name': name });
}


Let me know what you think!

Carl

Answer

This is a case where regular expressions can help - they're designed for matching patterns in strings such as this. For this problem, you can use the following regex:

\/(\d+):([^:]*)$

This is made up of:

  • \/ - an escaped / - the starting slash
  • (\d+) - at least one digit, inside a capturing group, to capture the ID
  • : - literally a colon
  • ([^:]*) - a capturing group looking for anything other than a colon, to capture the name
  • $ - the end of the string

To use this in your code, you can do so as follows:

angular.forEach(obj, function(val, key) {
    //note the extra / at the start and end, denoting this as a regular expression
    //in javascript
    var result = /\/(\d+):([^:]*)$/.exec(key);
    var id = result[1];
    var name = result[2];

    newObj.push({ 'id': id, 'name': name });
}

result is an array, where indices 1 and 2 correspond to the capturing groups in the regex.

For a visualisation of what's happening, and more of a breakdown of the regular expression, there are a number of online tools such as regex101.com which can help.