'Rescript retrieving a single character from a string as a char type
How do you get a char from a string. This returns a string
Js.String2.charAt("abc", 0) //=> returns "a" not 'a'
While this returns the character code (int)
String.get("abc", 0) //=> returns 97 not 'a'
The second one makes sense, if you look at the implementation
function get(s, i) {
if (i >= s.length || i < 0) {
throw {
RE_EXN_ID: "Invalid_argument",
_1: "index out of bounds",
Error: new Error()
};
}
return s.charCodeAt(i);
}
instead of reading the description
get(s, n) returns as a string the character at the given index number.
Rescript version 9
EDIT:
in javascript one could accomplish this with
"abc".charAt(0) //=> returns 'a'
and I could create the bindings for this, but I am surprised that I would need to. (given the libraries String and String2)
Solution 1:[1]
One option is creating your own binding:
@send external charAt : (string, int) => char = "charAt"
and use it
charAt("abc", 0) //=> 'a'
generates the JavaScript
"abc".charAt(0);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | akaphenom |
