How to get the middle character from a string in Node.js

2 Answers

0 votes
const s = "abcdefg";
   
const index = Math.floor(s.length / 2) ;
   
console.log(s[index]); 

     
     
/*
run:
     
d
     
*/
 

 



answered Sep 10, 2024 by avibootz
0 votes
const s = "nodejs";

// Example 1
let index = Math.floor(s.length / 2) ;
console.log(s[index]); 

// Example 2
const len = s.length;
index = Math.floor(len / 2) ;

if (len % 2 == 1) {
    console.log(s[index]); 
} else if (len % 2 == 0) {
            console.log(s[index - 1], s[index]); 
       }


     
/*
run:
     
e
d e
     
*/
 

 



answered Sep 10, 2024 by avibootz

Related questions

...