TOP

Snake Case Function for LibreOffice Calc

YLC Utilities logo

SNAKECASE() Description

The SNAKECASE() function is designed to combine words using underscores, i.e. a single word is returned as a result, e.g. «snake_case_function» .

Snake Case splits a string of words separated by spaces, hyphens, underscores, or case changes, then converts those words to lowercase and concatenates them with an underscore separator ("_").

The SNAKECASE() function can be useful in programming to convert variable names according to accepted code writing conventions (coding conventions) .


StarBASIC code for function Snake Case

Here is the macro code to create a custom function that can convert text into single words separated by underscores (Snake Case) in LibreOffice Calc.

Open the menu Tools - Macros - Edit Macros..., select Module1 and copy the following text into the module:

Function SnakeCase(ByVal str As String) As String
  'moonexcel.com.ua
  Dim words As Variant
  Dim FCalc  As Object
  
  FCalc = CreateUnoService("com.sun.star.sheet.FunctionAccess")
  
  str = Replace(str,"-"," ")
  str = Replace(str,"_"," ")  
  str = FCalc.callFunction("TRIM", Array(str))  
  str = FCalc.callFunction("REGEX", Array(str,"([:lower:])([:upper:])","$1 $2","g"))
    
  str = LCase(str)
  words = Split(str, " ")            
    
  SnakeCase = Join(words,"_")
End Function

Then close Macro Editor, return to LibreOffice Calc and use our new function in any cell.

Using the extension

You can also use the feature SNAKECASE() by installing the free extension YouLibreCalc.oxt or its full-featured version YLC_Utilities.oxt .

After that, this function will be available in all files that will be opened in LibreOffice Calc.