How to move all special characters to the beginning of a string in TypeScript

2 Answers

0 votes
function moveSpecialCharactersToBeginning(s: string): string {
    const len: number = s.length; 
    let chars: string = "";
    let specialCharacters: string = ""; 
             
    for (let i = 0; i < len; i++) { 
        const ch: string = s[i]; 
        const alphanumeric: RegExp = /^[0-9a-zA-Z]+$/;
                   
        if (alphanumeric.test(ch)) {
            chars += ch; 
        } else {
            specialCharacters += ch; 
        }
    } 
     
    return specialCharacters + chars; 
} 
  
const s: string = "c++14$c&^java*(rust) php <>/python 3.14.2"; 
   
console.log(moveSpecialCharactersToBeginning(s));



/*
run:

"++$&^*()  <>/ ..c14cjavarustphppython3142" 

*/

 



answered Dec 12, 2025 by avibootz
0 votes
function moveSpecialCharactersToBeginning(s: string): string {
  let specials: string = "";
  let chars: string = "";

  for (const ch of s) {
    if (/[a-zA-Z0-9\s]/.test(ch)) {
      chars += ch;
    } else {
      specials += ch;
    }
  }

  return specials + chars;
}

const s: string = "c++20$c&^java*(rust) php <>/python 3.14.2";

console.log(moveSpecialCharactersToBeginning(s));



/*
run:

"++$&^*()<>/..c20cjavarust php python 3142" 

*/

 



answered Dec 13, 2025 by avibootz

Related questions

...