[英]Javascript: Get highest possible UTF8 character
我需要为前缀搜索获取尽可能高的UTF8字符。
我有一个这样的数据集:
A
Ba
Bf
C
现在,我可以通过指定开始和结束值来进行前缀搜索:
Start: B
End: B* where * should be the highest possible UTF8 character.
如何使用Javascript以编程方式获取此信息?
编辑:这是一个更好的示例:
我需要将此前缀发送到JSON RPC API。 因此,我无法在JS中进行实际比较。
但是如果我想对两个以B开头的字符串进行匹配,我会发送
Start: B
End: B?
在哪 是最大的UTF8字符。
如果是ASCII,则可以执行"B" + String.fromCharCode(255)
,但这仅用于ASCII。 我的字符串在UTF8中,在这种情况下,它与所有以B开头的字符串都不匹配。
根据您的代码,您可能不需要实际的最高UTF8代码点。
if ((input >= 'B') && (input < 'C')) { ... }
可以帮你
const maximumCodePoint = String.fromCodePoint(0x10ffff)
> String.fromCodePoint(0x10ffff + 1)
RangeError: Invalid code point 1114112
您可以使用>
比较运算符在JavaScript中对字符串开头进行UTF代码点比较。 所以你可以使用
search >= "B" && search < "C"
,但简单
search.test(/^B.*/)
要么
search.charAt(0) == "B"
也应该这样做。
在我看来,您想要:
var datas = [
'A',
'Bf',
'Ba',
'C'
];
// Create an array with char codes prefixed with "B" but it returns
// for the second string. For example, for B*, it returns the char code of *.
var datasB = datas.map( function( data ) {
if ( data.charAt( 0 ) === 'B' ) {
return data.substr( 1 ).charCodeAt( 0 );
}
} ).filter( Boolean );
// The `filter( Boolean )` removes the falsy values (undefined)
// This technique is very efficient to get the maximum value of an array
var max = Math.max.apply( Math, datasB );
John Resig对获得数组最大值的技术的启发。
如果要确定范围,可以使用\
。
MyRange("foo", "foo\uffff")
将查找以foo
开头的所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.