builtin_regexp.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package otto
  2. import (
  3. "fmt"
  4. )
  5. // RegExp
  6. func builtinRegExp(call FunctionCall) Value {
  7. pattern := call.Argument(0)
  8. flags := call.Argument(1)
  9. if object := pattern._object(); object != nil {
  10. if object.class == classRegExp && flags.IsUndefined() {
  11. return pattern
  12. }
  13. }
  14. return toValue_object(call.runtime.newRegExp(pattern, flags))
  15. }
  16. func builtinNewRegExp(self *_object, argumentList []Value) Value {
  17. return toValue_object(self.runtime.newRegExp(
  18. valueOfArrayIndex(argumentList, 0),
  19. valueOfArrayIndex(argumentList, 1),
  20. ))
  21. }
  22. func builtinRegExp_toString(call FunctionCall) Value {
  23. thisObject := call.thisObject()
  24. source := thisObject.get("source").string()
  25. flags := []byte{}
  26. if thisObject.get("global").bool() {
  27. flags = append(flags, 'g')
  28. }
  29. if thisObject.get("ignoreCase").bool() {
  30. flags = append(flags, 'i')
  31. }
  32. if thisObject.get("multiline").bool() {
  33. flags = append(flags, 'm')
  34. }
  35. return toValue_string(fmt.Sprintf("/%s/%s", source, flags))
  36. }
  37. func builtinRegExp_exec(call FunctionCall) Value {
  38. thisObject := call.thisObject()
  39. target := call.Argument(0).string()
  40. match, result := execRegExp(thisObject, target)
  41. if !match {
  42. return nullValue
  43. }
  44. return toValue_object(execResultToArray(call.runtime, target, result))
  45. }
  46. func builtinRegExp_test(call FunctionCall) Value {
  47. thisObject := call.thisObject()
  48. target := call.Argument(0).string()
  49. match, _ := execRegExp(thisObject, target)
  50. return toValue_bool(match)
  51. }
  52. func builtinRegExp_compile(call FunctionCall) Value {
  53. // This (useless) function is deprecated, but is here to provide some
  54. // semblance of compatibility.
  55. // Caveat emptor: it may not be around for long.
  56. return Value{}
  57. }