Home > Software design >  Javascript : Cutting/Removing excess characters from a string if it exceeds the Limit
Javascript : Cutting/Removing excess characters from a string if it exceeds the Limit

Time:11-11

This question is a bit tricky to explain. Say i have an variable whose length is dynamic meaning it is random,i want to change its length to the first 5 or a certain amount of characters regardless of the length of the characters existing in the variable. I hope i could explain what i am trying to do

.________________________________________________________________________. I really dont know which direction to go in or what step to take in order to reach my goal but i just copy/pasted some random code of the internet that didn't work so i did not think it is of any importance to include in this query,but i could share on demand

CodePudding user response:

Pseudo code...

const str = "the string";
const start = 0;
// const end = str.length;
str.substring(start, (optional) end);

So if you want just first five characters, you do something like

str.substring(0, 5);

CodePudding user response:

If it's only integers (numbers) you could simply generate a random whole number between 11111 and 99999 (so it's always 5 digits), like this:

let x = Math.floor((Math.random() * 99999)   11111);
  • Related