1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-16 11:37:36 +02:00
ferret/pkg/stdlib/strings/trim.go

72 lines
2.0 KiB
Go
Raw Normal View History

package strings
import (
"context"
2018-10-14 19:06:27 +02:00
"strings"
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
)
2018-10-14 19:06:27 +02:00
// Trim returns the string value with whitespace stripped from the start and/or end.
// @param value (String) - The string.
// @param chars (String) - Overrides the characters that should be removed from the string. It defaults to \r\n \t.
// @returns (String) - The string without chars on both sides.
func Trim(_ context.Context, args ...core.Value) (core.Value, error) {
err := core.ValidateArgs(args, 1, 2)
if err != nil {
return values.EmptyString, err
}
text := args[0].String()
if len(args) > 1 {
2018-09-26 00:06:45 +02:00
return values.NewString(strings.Trim(text, args[1].String())), nil
}
2018-09-26 00:06:45 +02:00
return values.NewString(strings.TrimSpace(text)), nil
}
2018-10-14 19:06:27 +02:00
// LTrim returns the string value with whitespace stripped from the start only.
// @param value (String) - The string.
// @param chars (String) - Overrides the characters that should be removed from the string. It defaults to \r\n \t.
// @returns (String) - The string without chars at the left-hand side.
func LTrim(_ context.Context, args ...core.Value) (core.Value, error) {
err := core.ValidateArgs(args, 1, 2)
if err != nil {
return values.EmptyString, err
}
text := args[0].String()
chars := " "
if len(args) > 1 {
chars = args[1].String()
}
return values.NewString(strings.TrimLeft(text, chars)), nil
}
2018-10-14 19:06:27 +02:00
// RTrim returns the string value with whitespace stripped from the end only.
// @param value (String) - The string.
// @param chars (String) - Overrides the characters that should be removed from the string. It defaults to \r\n \t.
// @returns (String) - The string without chars at the right-hand side.
func RTrim(_ context.Context, args ...core.Value) (core.Value, error) {
err := core.ValidateArgs(args, 1, 2)
if err != nil {
return values.EmptyString, err
}
text := args[0].String()
chars := " "
if len(args) > 1 {
chars = args[1].String()
}
return values.NewString(strings.TrimRight(text, chars)), nil
}