How to move the first word to the end of a string in TypeScript

3 Answers

0 votes
function move_first_word_to_end_of_string(s: string): string {
    s = s.trim();
    if (s.length === 0) return s;

    let i: number = 0;
    while (i < s.length && !/\s/.test(s[i])) {
        i++;
    }

    const firstWord: string = s.slice(0, i);
    const rest: string = s.slice(i).trim();

    return rest.length === 0 ? firstWord : rest + " " + firstWord;
}

const s = "Would you like to know more? (Explore and learn)";
const result: string = move_first_word_to_end_of_string(s);

console.log(result);

 
 
/*
run:
 
"you like to know more? (Explore and learn) Would" 
 
*/


 



answered Feb 5 by avibootz
edited Feb 5 by avibootz
0 votes
function moveFirstWordToEndOfString(s: string): string {
  const parts: string[] = s.trim().split(/\s+/);
 
  if (parts.length <= 1) {
    return s.trim();
  }
 
  const first: string = parts.shift()!;
  parts.push(first);
 
  return parts.join(" ");
}
 
const s = "Would you like to know more? (Explore and learn)";
const result: string = moveFirstWordToEndOfString(s);
 
console.log(result);
 
 
 
/*
run:
 
you like to know more? (Explore and learn) Would
 
*/

 



answered Feb 5 by avibootz
edited Feb 5 by avibootz
0 votes
function moveFirstWordToEndOfString(s: string): string {
  const parts: string[] = s.trim().split(/\s+/);
  if (parts.length <= 1) return s;
 
  return [...parts.slice(1), parts[0]].join(" ");
}
 
const s = "Would you like to know more? (Explore and learn)";
const result: string = moveFirstWordToEndOfString(s);
 
console.log(result);
 
 
  
  
/*
run:
  
"you like to know more? (Explore and learn) Would" 
  
*/

 



answered Feb 5 by avibootz
edited Feb 5 by avibootz
...