Skip to content

Remove last part of String in Javascripts

I’m struggling with a code in JS in order to extract the last part of a String.

Examples of the input strings could be: 



and I need the first part until the second . like this





You can use combination of split, slice & join to do this

var arr = ["", "Event.DEAudience-90c92fe9-9b10-7fc8-9b10-7eb778f68888.NNNNNNNN"];

for (var i = 0; i < arr.length; i++) {
  console.log(arr[i].split(".").slice(0, -1).join("."))


split(".") returns an array

["Event", "DEAudience-90c92fe9-9b10-7fc8-9b10-7eb778f68888", "NNNNNNNN"]

You only need elements up to second last element from this array. For that we can use slice method slice(0, -1), here we are passing range of elements to select. 0 denotes the start index and -1 (negative indexing) end index denotes last element. Slicing method return elements in the array from start index up to end index (not inclusive). So we’ll get,

["Event", "DEAudience-90c92fe9-9b10-7fc8-9b10-7eb778f68888"]

Now we need to convert this back to string along with the dots. For that we can use join(".") method. It will join elements in the array with "." and return as a string