Strings in GoloScript
Complete guide to string manipulation in GoloScript.
Multiline Strings
GoloScript supports multiline strings with """ syntax:
let helpText = """
Usage: myapp [OPTIONS] COMMAND
Options:
-h, --help Show this help message
-v, --version Show version information
Commands:
start Start the application
stop Stop the application
"""
println(helpText)
Use Cases: Documentation, SQL queries, JSON/XML templates, ASCII art
Escape Sequences
GoloScript supports standard escape sequences to include special characters in strings.
Available Escape Sequences
| Sequence | Description | Example |
|---|---|---|
\" |
Double quote | "He said: \"Hello\"" |
\\ |
Backslash | "C:\\Users\\Alice" |
\n |
Newline | "Line 1\nLine 2" |
\t |
Tab | "Col1\tCol2\tCol3" |
\' |
Apostrophe (optional) | "It\'s time" |
\0 |
Null character | "End\0" |
Practical Examples
Double Quotes
let quote = "He said: \"Hello everyone!\""
println(quote)
# Prints: He said: "Hello everyone!"
Windows File Paths
let path = "C:\\Users\\Alice\\Documents\\file.txt"
println(path)
# Prints: C:\Users\Alice\Documents\file.txt
Multiline Text with \n
let multiline = "Line 1\nLine 2\nLine 3"
println(multiline)
# Prints:
# Line 1
# Line 2
# Line 3
Tabs
let tabbed = "Name:\t\"Alice\"\nAge:\t30\nCity:\t\"Paris\""
println(tabbed)
# Prints:
# Name: "Alice"
# Age: 30
# City: "Paris"
JSON with Escapes
let json = "{\"name\":\"Bob\",\"message\":\"Hello \\\"World\\\"\"}"
println(json)
# Prints: {"name":"Bob","message":"Hello \"World\""}
let parsed = fromJSON(json)
println("Name:", parsed: name()) # Bob
println("Message:", parsed: message()) # Hello "World"
Formatted JSON
let prettyJson = "{\n\t\"title\": \"Golo\",\n\t\"version\": 2.0,\n\t\"active\": true\n}"
println(prettyJson)
# Prints:
# {
# "title": "Golo",
# "version": 2.0,
# "active": true
# }
All Escapes Together
let all = "Tab:\\t Newline:\\n Quote:\\\" Backslash:\\\\ SingleQuote:\\' Null:\\0End"
println(all)
# Prints: Tab:\t Newline:\n Quote:\" Backslash:\\ SingleQuote:\' Null:\0End
String Methods
Basic Methods
let text = "Hello World"
# Length
text: length() # 11
# Character access
text: charAt(0) # "H"
text: substring(0, 4) # "Hello" (end inclusive)
# Search
text: contains("World") # true
text: startsWith("Hello") # true
text: endsWith("World") # true
text: indexOf("o") # 4
text: lastIndexOf("o") # 7
Transformations
let text = " Hello World "
# Case
text: toLowerCase() # " hello world "
text: toUpperCase() # " HELLO WORLD "
# Whitespace
text: trim() # "Hello World"
# Replacement
text: replace("World", "Golo") # " Hello Golo "
text: replaceAll(" ", "_") # "__Hello_World__"
Split and Join
# Split
let words = "one,two,three": split(",")
# β ["one", "two", "three"]
# Iteration
foreach word in words {
println(word)
}
Comparison
let str1 = "Hello"
let str2 = "HELLO"
# Case sensitive
str1 == str2 # false
# Case insensitive
str1: equalsIgnoreCase(str2) # true
Type Conversions
GoloScript offers several approaches for converting strings to numbers, each with its advantages and use cases.
String β Int Conversion
There are 4 ways to convert a string to an integer:
1. int() Function - Throws Exception
# Imperative style
try {
let num = int("42")
println("Result:", num) # 42
} catch (e) {
println("Error:", e)
}
Characteristics:
- Global builtin function
- Throws exception on error
- Requires
try-catchfor error handling - Usage: imperative code where error is exceptional
2. toInt() Method - Throws Exception
# Object-oriented style
try {
let num = "123": toInt()
println("Result:", num) # 123
} catch (e) {
println("Error:", e)
}
Characteristics:
- Method on String objects
- Throws exception on error
- Object-oriented syntax
- Requires
try-catchfor error handling
3. parseInt() Function - Returns Result
import gololang.Errors
let result = parseInt("999")
println("Result:", result)
if isOk(result) {
println("Value:", result: value()) # 999
}
if isError(result) {
println("Error:", result: message())
}
Characteristics:
- Function from
gololang.Errorsmodule - Returns
Result[Int, String] - No exception, error as value
- Allows functional composition
4. either() Function - Pattern Matching (β RECOMMENDED)
import gololang.Errors
let inputs = array("42", "invalid", "-100", "xyz", "0")
foreach input in inputs {
let result = parseInt(input)
either(result,
|value| -> println("β", input, "->", value),
|error| -> println("β", input, "-> Error")
)
}
Characteristics:
- Handles both cases (success/failure) elegantly
- No
if/elseneeded - Declarative and expressive style
- Best practice for Result
String β Float Conversion
GoloScript offers 3 approaches for converting a string to floating-point number:
1. float() Function - Throws Exception
try {
let f = float("3.14159")
println("Result:", f) # 3.14159
} catch (e) {
println("Error:", e)
}
2. toFloat() Method - Throws Exception
try {
let f = "2.71828": toFloat()
println("Result:", f) # 2.71828
} catch (e) {
println("Error:", e)
}
3. parseFloat() Function - Result (β RECOMMENDED)
import gololang.Errors
let inputs = array("1.618", "bad", "-273.15", "0.0", "xyz")
foreach input in inputs {
let result = parseFloat(input)
either(result,
|value| -> println("β", input, "->", value),
|error| -> println("β", input, "-> Error")
)
}
Comparison and Recommendations
| Approach | Style | Error Handling | Use Case |
|---|---|---|---|
int() / toInt() |
Imperative | Exception | Exceptional error, imperative code |
float() / toFloat() |
Imperative | Exception | Exceptional error, imperative code |
parseInt() + either() |
Functional | Result | β Validation, parsing user input (recommended) |
parseFloat() + either() |
Functional | Result | β Validation, parsing user input (recommended) |
General Recommendation:
- Use
parseInt()/parseFloat()+either()for safer and more expressive code - These functions allow functional composition with
mapResult,flatMapResult, etc. - Error as value avoids unexpected exceptions
Type Detection
let input = "123"
# Checking
input: isNumeric() # true
input: isInt() # true
input: isFloat() # false (it's an integer)
let decimal = "3.14"
decimal: isNumeric() # true
decimal: isFloat() # true
Convert to Boolean
"true": toBool() # true
"false": toBool() # false
# Contextual check
let answer = "yes"
if answer: toLowerCase() == "yes" or answer: toLowerCase() == "true" {
# Treat as true
}
Utility Functions
Email Validation
function isValidEmail = |email| {
let trimmed = email: trim()
if not trimmed: contains("@") {
return false
}
let parts = trimmed: split("@")
if parts: length() != 2 {
return false
}
let domain = parts: get(1)
return domain: contains(".")
}
isValidEmail("john@example.com") # true
isValidEmail("invalid.email") # false
Data Type Detection
function whatIsIt = |item| {
return match {
when item: contains("@") then "email"
when item: startsWith("http://") then "HTTP URL"
when item: startsWith("https://") then "HTTPS URL"
when item: startsWith("+33") then "French phone"
otherwise "unknown"
}
}
whatIsIt("john@example.com") # "email"
whatIsIt("https://example.com") # "HTTPS URL"
Word Counter
function countWords = |text| {
let trimmed = text: trim()
if trimmed: isEmpty() {
return 0
}
return trimmed: split(" "): length()
}
countWords("Hello world from Golo") # 4
Title Case
function toTitleCase = |text| {
let words = text: toLowerCase(): split(" ")
var result = ""
var first = true
foreach word in words {
if not first {
result = result + " "
}
if word: length() > 0 {
let firstChar = word: charAt(0): toUpperCase()
let rest = word: substring(1)
result = result + firstChar + rest
}
first = false
}
return result
}
toTitleCase("hello world") # "Hello World"
Truncate
function truncate = |text, maxLen| {
if text: length() <= maxLen {
return text
}
if maxLen <= 3 {
return text: substring(0, maxLen - 1)
}
return text: substring(0, maxLen - 4) + "..."
}
truncate("This is a long sentence", 15) # "This is a lo..."
HTML Sanitization
function sanitize = |input| {
return input: trim()
: replaceAll("<", "<")
: replaceAll(">", ">")
}
sanitize("<script>alert('xss')</script>")
# "<script>alert('xss')</script>"
Slugification
function slugify = |text| {
return text: toLowerCase()
: trim()
: replaceAll(" ", "-")
}
slugify("Hello World") # "hello-world"
File Extension
function getFileExtension = |filename| {
let dotIndex = filename: lastIndexOf(".")
if dotIndex == -1 {
return ""
}
return filename: substring(dotIndex + 1)
}
getFileExtension("document.pdf") # "pdf"
getFileExtension("readme") # ""
Best Practices
β Do
-
Always validate before conversion
if input: isInt() { let num = input: toInt() # Use num safely } -
Use trim() to clean input
let clean = userInput: trim() -
Prefer equalsIgnoreCase() for case-insensitive comparison
if answer: equalsIgnoreCase("yes") { # ... }
β Donβt
-
Donβt convert without checking
# β Risk of error let num = input: toInt() # β Safe if input: isInt() { let num = input: toInt() } -
Donβt forget isEmpty()
# β Error if empty let words = text: split(" ") # β Check first if not text: trim(): isEmpty() { let words = text: split(" ") }
Summary
Strings in GoloScript offer:
- Multiline:
"""syntax for long texts - Rich methods: 20+ useful methods
- Safe conversions: isInt(), isFloat(), toBool()
- Utilities: Validation, sanitization, transformation
Recommendation: Always validate before converting, use method chaining for elegant code.
Β© 2026 GoloScript Project | Built with Gu10berg
Subscribe: π‘ RSS | βοΈ Atom