forked from MontFerret/ferret
/
substitute.go
42 lines (33 loc) · 1.01 KB
/
substitute.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package strings
import (
"context"
"strings"
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
)
// Substitute replaces search values in the string value.
// @params text (String) - The string to modify
// @params search (String) - The string representing a search pattern
// @params replace (String) - The string representing a replace value
// @param limit (Int) - The cap the number of replacements to this value.
// @return (String) - Returns a string with replace substring.
func Substitute(_ context.Context, args ...core.Value) (core.Value, error) {
err := core.ValidateArgs(args, 2, 4)
if err != nil {
return values.EmptyString, err
}
text := args[0].String()
search := args[1].String()
replace := ""
limit := -1
if len(args) > 2 {
replace = args[2].String()
}
if len(args) > 3 {
if args[3].Type() == core.IntType {
limit = int(args[3].(values.Int))
}
}
out := strings.Replace(text, search, replace, limit)
return values.NewString(out), nil
}