Crotus B Crotus B - 4 months ago 12
HTML Question

String manipulation with JavaScript from the end of the string

I've been having trouble trying to apply different JavaScript string manipulation solutions to my specific problem:

string str = ":2 E/4 :2 G/4 |:2 G/4 :2 F/4"


From the end of the string, I want to remove all the way up to the first
:
that is found.

1 removal:

":2 E/4 :2 G/4 |:2 G/4 "


2 removals:

":2 E/4 :2 G/4 |"


3 removals:

":2 E/4 "


How do I do this?

Answer

The solution using String.split, Array.slice and Array.join functions:

/**
 * @param string str Input string with 'colons'
 * @param number removals Number of removals
 * @returns string
 */
var sliceToColon = function (str, removals) {
    var parts = str.split(":");
    return parts.slice(0, -removals).join(":");
}

console.log(sliceToColon(":2 E/4 :2 G/4 |:2 G/4 :2 F/4", 1)); // :2 E/4 :2 G/4 |:2 G/4 
console.log(sliceToColon(":2 E/4 :2 G/4 |:2 G/4 :2 F/4", 2)); // :2 E/4 :2 G/4 |
console.log(sliceToColon(":2 E/4 :2 G/4 |:2 G/4 :2 F/4", 3)); // :2 E/4 
Comments