Looking to get a head start on your next software interview? Pickup a copy of the best book to prepare: Cracking The Coding Interview!
val regex = js("RegExp('hello', 'g')")
The first argument to the `RegExp` constructor is the pattern you want to match, and the second argument is a string of flags that modify the behavior of the regular expression. In this case, we are using the “g” flag to match all occurrences of the pattern.
Once you have created the regular expression object, you can use the `match` method of the string to search for matches. For example, to find all occurrences of the word “hello” in a string, you can use the following code:
val str = "hello world, hello Kotlin"
val matches = str.match(regex)
The `match` method returns an array of all matches found in the string. In this case, the `matches` variable will contain an array with two elements, “hello” and “hello”.
You can also use the `replace` method of the string to replace all occurrences of a pattern with a new string. For example, to replace all occurrences of the word “hello” with the word “hi” in a string, you can use the following code:
val newStr = str.replace(regex, "hi")
The `replace` method returns a new string with all occurrences of the pattern replaced with the new string. In this case, the `newStr` variable will contain the string “hi world, hi Kotlin”.