Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep only first n characters in a string?

Tags:

javascript

Is there a way in JavaScript to remove the end of a string?

I need to only keep the first 8 characters of a string and remove the rest.

like image 999
user978905 Avatar asked Oct 10 '11 05:10

user978905


People also ask

How do you get the first n characters of a string?

To access the first n characters of a string in Java, we can use the built-in substring() method by passing 0, n as an arguments to it. 0 is the first character index (that is start position), n is the number of characters we need to get from a string. Note: The extraction starts at index 0 and ends before index 3.

How do you extract the first 5 characters from the string str?

You can use the substr function like this: echo substr($myStr, 0, 5); The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.

How do you extract the first 10 characters in Python?

To access the first n characters of a string in Python, we can use the subscript syntax [ ] by passing 0:n as an arguments to it. 0 is the starting position of an index. n is the number of characters we need to extract from the starting position (n is excluded).

How do you get the first 20 characters of a string?

slice() method to get the first N characters of a string, e.g. str. slice(0, 3) . The slice() method takes the start and stop indexes as parameters and returns a new string containing a slice of the original string.


1 Answers

const result = 'Hiya how are you'.substring(0,8); console.log(result); console.log(result.length);

You are looking for JavaScript's String method substring

e.g.

'Hiya how are you'.substring(0,8); 

Which returns the string starting at the first character and finishing before the 9th character - i.e. 'Hiya how'.

substring documentation

like image 137
Shad Avatar answered Sep 30 '22 02:09

Shad