github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/strings/trim.go (about)

     1  package strings
     2  
     3  import (
     4  	"context"
     5  	"strings"
     6  
     7  	"github.com/MontFerret/ferret/pkg/runtime/core"
     8  	"github.com/MontFerret/ferret/pkg/runtime/values"
     9  )
    10  
    11  // TRIM returns the string value with whitespace stripped from the start and/or end.
    12  // @param {String} str - The string.
    13  // @param {String} chars - Overrides the characters that should be removed from the string. It defaults to \r\n \t.
    14  // @return {String} - The string without chars on both sides.
    15  func Trim(_ context.Context, args ...core.Value) (core.Value, error) {
    16  	err := core.ValidateArgs(args, 1, 2)
    17  
    18  	if err != nil {
    19  		return values.EmptyString, err
    20  	}
    21  
    22  	text := args[0].String()
    23  
    24  	if len(args) > 1 {
    25  		return values.NewString(strings.Trim(text, args[1].String())), nil
    26  	}
    27  
    28  	return values.NewString(strings.TrimSpace(text)), nil
    29  }
    30  
    31  // LTRIM returns the string value with whitespace stripped from the start only.
    32  // @param {String} str - The string.
    33  // @param {String} chars - Overrides the characters that should be removed from the string. It defaults to \r\n \t.
    34  // @return {String} - The string without chars at the left-hand side.
    35  func LTrim(_ context.Context, args ...core.Value) (core.Value, error) {
    36  	err := core.ValidateArgs(args, 1, 2)
    37  
    38  	if err != nil {
    39  		return values.EmptyString, err
    40  	}
    41  
    42  	text := args[0].String()
    43  	chars := " "
    44  
    45  	if len(args) > 1 {
    46  		chars = args[1].String()
    47  	}
    48  
    49  	return values.NewString(strings.TrimLeft(text, chars)), nil
    50  }
    51  
    52  // RTRIM returns the string value with whitespace stripped from the end only.
    53  // @param {String} str - The string.
    54  // @param {String} chars - Overrides the characters that should be removed from the string. It defaults to \r\n \t.
    55  // @return {String} - The string without chars at the right-hand side.
    56  func RTrim(_ context.Context, args ...core.Value) (core.Value, error) {
    57  	err := core.ValidateArgs(args, 1, 2)
    58  
    59  	if err != nil {
    60  		return values.EmptyString, err
    61  	}
    62  
    63  	text := args[0].String()
    64  	chars := " "
    65  
    66  	if len(args) > 1 {
    67  		chars = args[1].String()
    68  	}
    69  
    70  	return values.NewString(strings.TrimRight(text, chars)), nil
    71  }