Golang : Strip slashes from string example
A quick post on how to get an equivalent to PHP's stripslashes()
function in Golang. Basically in PHP, the stripslashes()
function will remove any backslashes from a string. \'
becomes '
and double backslashes \\
are made into a single backslash \
.
Example from official PHP documentation :
<?php
$str = "Is your name O\'reilly?";
echo stripslashes($str);
?>
Output :
Is your name O'reilly?
To achieve similar result in Golang, use this example :
package main
import (
"fmt"
"strings"
)
func main() {
// use backtick ` instead of double quote "
// otherwise, you will get this error message
// unknown escape sequence: '
str := `Is your name O\'reilly?`
fmt.Println(str)
stripSlash := strings.Replace(str, "\\", "", -1)
fmt.Println(stripSlash)
}
Output :
Is your name O\'reilly?
Is your name O'reilly?
NOTE :
Golang's strconv.Unquote()
function does not strip backslashes. What it does is to transform the a Go character literal to the corresponding one-character.
Happy coding!
Reference :
See also : Golang : unknown escape sequence error
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+13.1k Golang : On enumeration
+5.6k Golang : Warp text string by number of characters or runes example
+16.4k Golang : Read data from config file and assign to variables
+4.3k Golang : Issue HTTP commands to server and port example
+4.2k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+33.6k Golang : Save image to PNG, JPEG or GIF format.
+7.7k Golang : Write multiple lines or divide string into multiple lines
+17.6k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+4.7k Linux : Disable and enable IPv4 forwarding
+20.8k Golang : Read directory content with filepath.Walk()
+32.5k Golang : Proper way to set function argument default value
+11.5k Golang : Transform comma separated string to slice example