Categories
JavaScript

JavaScript string manipulation

  • Lowercase / Uppercase  
     my_string.toUpperCase() 
     my_string.toLowerCase() 
  • Find first occurrence of substring  
     my_string.indexOf() 
     my_string.lastIndexOf() 
  • Return a portion of your string by indexes  
     string.slice(start, end); 
      Indexes can be negative so you start counting from the end of the string
  • Find index using regular expressions       
     my_regular_expression = /To be/;      
     my_string = “To be or not to be”;      
     sub_str_index = my_string.search(my_regular_expression);      // Finds the first  occurrence index of the reg expr string, or -1 if not found
  • Replacing text       
     date = ‘10.28.2008’;      
     replaceRegEx = /./g;   Looking for a “.” g for globally and not just the first instance    
     date.replace(replaceRegex, ‘/’);   Replace “.” with /

Leave a Reply

Your email address will not be published. Required fields are marked *