Is There A Way To Mutate Strings Without Using All Kinds Of Different Methods?

- 1 answer

I have a project in which i need to split an ID into two separate IDs. The first Id has a static length of 20 chars and the second is variable.

I currently have the following code in place:

mergedUUID = "12345678902345678900123";
const serverUUIDlength = 20;
const cameraId = mergedUUID.slice(serverUUIDlength);
const deviceId = mergedUUID.substring(serverUUIDlength);

Resulting in deviceId being 12345678902345678900 and cameraId123.

But this feels "dumb", I use these two different methods while they are doing practically the same, it there a better (more clean) way?



You are confusing two different methods. While they are really alike there are subtle difference between them.

substring has something of a foolproof method to 'always' work. For example it swaps it's parameters around if the given startIndex is greater than the endIndex. Slice in this case would have returned an empty string.

Example code:

var text = 'Mozilla';
console.log(text.substring(5, 2)); // => "zil" 
console.log(text.slice(5, 2));     // => ""

To answer your question; you should consider using one method, not both. That's the better way.

For additional documentation, click here.