Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,884 questions

51,810 answers

573 users

How to reverse the middle N characters of a string in TypeScript

2 Answers

0 votes
function reverse_middle_N_characters(str: string, N: number) { 
    if (N <= 0 || N > str.length) {
        return str; 
    }

    const start: number = Math.floor((str.length - N) / 2);
    const end: number = start + N;

    const beforeMiddle: string = str.slice(0, start);
    const middle: string = str.slice(start, end).split('').reverse().join('');
    const afterMiddle: string = str.slice(end);

    return beforeMiddle + middle + afterMiddle;
} 
    
     
let s: string = "abCDEFgh"; 
const N: number = 4; 
      
console.log(reverse_middle_N_characters(s, N));


   
/*
run:
       
"abFEDCgh" 

*/

 



answered Sep 12, 2024 by avibootz
0 votes
function reverse_middle_N_characters(str: string, N: number) { 
    if (N <= 0 || N > str.length) {
        return str; 
    }

    const len = s.length;
    const mid = (len - N) / 2; 
    let tmp = "";
   
    for (let i = 0; i < mid; i++) 
        tmp += s[i]; 
     
    for (let i = mid + N - 1; i >= mid; i--) 
        tmp += s[i]; 
     
    for (let i = mid + N; i < len; i++) 
         tmp += s[i];
       
    return tmp;
} 
    
     
let s: string = "abCDEFgh"; 
const N: number = 4; 
      
console.log(reverse_middle_N_characters(s, N));


   
/*
run:
       
"abFEDCgh" 

*/

 



answered Sep 12, 2024 by avibootz
...