ScriptsConnect ScriptsConnect - 1 year ago 48
Javascript Question

How to remove all characters before specific character in array data

I have a comma-separated string being pulled into my application from a web service, which lists a user's roles. What I need to do with this string is turn it into an array, so I can then process it for my end result. I've successfully converted the string to an array with jQuery, which is goal #1. Goal #2, which I don't know how to do, is take the newly created array, and remove all characters before any array item that contains '/', including '/'.

I created a simple work-in-progress JSFiddle:

The string I receive is the following:


in the string above can change, and may be
, etc.

To convert to an array, I've done the following:

var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');

, I get the following result:

["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"]

I'm now at the point where I need the code to look at each index of array, and if
exists, remove all characters before

I've searched for a solution, but the JS solutions I've found are for removing characters after a particular character, and are not quite what I need to get this done.

Answer Source

You can use a single for loop to go through the array, then split() the values by / and retrieve the last value of that resulting array using pop(). Try this:

for (var i = 0; i < currentUserRole.length; i++) {
    var data = currentUserRole[i].split('/');
    currentUserRole[i] = data.pop();

Example fiddle

The benefit of using pop() over an explicit index, eg [1], is that this code won't break if there are no or multiple slashes within the string.