github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/strings/substitute.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  	"github.com/MontFerret/ferret/pkg/runtime/values/types"
    10  )
    11  
    12  // SUBSTITUTE replaces search values in the string value.
    13  // @param {String} str - The string to modify
    14  // @param {String} search - The string representing a search pattern
    15  // @param {String} replace - The string representing a replace value
    16  // @param {Int} limit - The cap the number of replacements to this value.
    17  // @return {String} - Returns a string with replace substring.
    18  func Substitute(_ context.Context, args ...core.Value) (core.Value, error) {
    19  	err := core.ValidateArgs(args, 2, 4)
    20  
    21  	if err != nil {
    22  		return values.EmptyString, err
    23  	}
    24  
    25  	text := args[0].String()
    26  	search := args[1].String()
    27  	replace := ""
    28  	limit := -1
    29  
    30  	if len(args) > 2 {
    31  		replace = args[2].String()
    32  	}
    33  
    34  	if len(args) > 3 {
    35  		if args[3].Type() == types.Int {
    36  			limit = int(args[3].(values.Int))
    37  		}
    38  	}
    39  
    40  	out := strings.Replace(text, search, replace, limit)
    41  
    42  	return values.NewString(out), nil
    43  }