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,941 questions

51,879 answers

573 users

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

2 Answers

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

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

 



answered Aug 16, 2019 by avibootz
edited Dec 12, 2025 by avibootz
0 votes
function moveSpecialCharactersToBeginning(s) {
  let specials = "";
  let chars = "";

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

  return specials + chars;
}

const s = "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

...