簡體   English   中英

Javascript:獲取盡可能高的UTF8字符

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM