Is There A Way To Mutate Strings Without Using All Kinds Of Different Methods?
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 cameraId
123
.
But this feels "dumb", I use these two different methods while they are doing practically the same, it there a better (more clean) way?
Answer
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.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM