Skip to content
Advertisement

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:

Event.DEAudience-90c92fe9-7fc8-f7ad-9b10-7eb778f6a857.id 

or

Event.DEAudience-90c92fe9-9b10-7fc8-9b10-7eb778f68888.NNNNNNNN

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

Event.DEAudience-90c92fe9-7fc8-f7ad-9b10-7eb778f6a857 

or

Event.DEAudience-90c92fe9-9b10-7fc8-9b10-7eb778f68888

Advertisement

Answer

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

var arr = ["Event.DEAudience-90c92fe9-7fc8-f7ad-9b10-7eb778f6a857.id", "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("."))
}

Working

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

Event.DEAudience-90c92fe9-9b10-7fc8-9b10-7eb778f68888
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement