Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

find the last occurrence of a character in a string javascript

str.lastIndexOf(searchValue[, fromIndex])
Comment

How to Get the Last Two Characters of a String in JavaScript

const str = 'Coding Beauty';

const last2 = str.slice(-2);
console.log(last2); // ty

// When we pass a negative number as an argument,
// slice() counts backward from the last string character to find the equivalent index.
// So passing -2 to slice() specifies a start index of str.length - 2.

const last2Again = str.slice(str.length - 2);
console.log(last2Again); // ty

// Note
// We can use substring() in place of slice() to get the first two characters of a string:

const str = 'Coding Beauty';
const last2 = str.substring(str.length - 2);
console.log(last2); // ty

// However, we have to manually calculate the start index ourselves with str.length - 2,
// which makes the code less readable.
// This is because unlike slice(), substring() uses 0 as the start index if a negative number is passed.

const str = 'Coding Beauty';

// -2 is negative, 0 used as start index
const notLast2 = str.substring(-2);

console.log(notLast2); // Coding Beauty
Comment

PREVIOUS NEXT
Code Example
Javascript :: storybook react router 
Javascript :: remove first element of array javascript 
Javascript :: convert milliseconds to time javascript 
Javascript :: js stop submit 
Javascript :: javascript read consol input 
Javascript :: dayjs after 
Javascript :: Javascript make alert box 
Javascript :: Get the url and parse or url.parse deprecated solved 
Javascript :: how to get a due date from current date in javascript 
Javascript :: carousel react 
Javascript :: javascript array.from 
Javascript :: change image onclick js 
Javascript :: loop through nested json object typescript 
Javascript :: opencage reverse geocoding example 
Javascript :: email regex javascript 
Javascript :: how to read json file with file input html 
Javascript :: cache request in vue 
Javascript :: javascript uppercase function 
Javascript :: react fragment inside map with key prop 
Javascript :: constructor function 
Javascript :: form.reset function in javascript 
Javascript :: react mui icons 
Javascript :: call python function from javascript 
Javascript :: how to show multiple image preview in jquery 
Javascript :: declaring constant in jsx 
Javascript :: js anonymous function es6 
Javascript :: define maxmum size of schema field in nodejs 
Javascript :: mongoose query using an arry 
Javascript :: videojs 100%width 
Javascript :: uncheck checkbox based on id js 
ADD CONTENT
Topic
Content
Source link
Name
1+1 =