JavaScript String normalize() 方法



JavaScript String normalize() 方法用於檢索給定輸入字串的 Unicode 規範化形式。如果輸入不是字串,則會在方法操作之前將其轉換為字串。預設規範化形式為“NFC”,即規範化形式規範化組合。

它接受一個名為“form”的可選引數,指定 Unicode 規範化形式,它可以取以下值:

  • NFC − 規範化形式規範化組合。
  • NFD − 規範化形式規範化分解。
  • NFKC − 規範化形式相容組合。
  • NFKD − 規範化形式相容分解。

語法

以下是 JavaScript String normalize() 方法的語法:

normalize(form)

引數

此方法接受一個名為“form”的引數,如下所述:

  • form (可選) − 指定 Unicode 規範化形式。

返回值

此方法返回一個新字串,其中包含輸入字串的 Unicode 規範化形式。

示例 1

如果我們省略form引數,則該方法使用預設規範化形式“NFC”。

在下面的示例中,我們使用 JavaScript String normalize() 方法來檢索給定字串“Tutorials Point”的 Unicode 規範化形式。由於我們省略了 form 引數,因此該方法使用預設規範化形式 NFC。

<html>
<head>
<title>JavaScript String normalize() Method</title>
</head>
<body>
<script>
   const str = "Tutorials Point";
   document.write("The given string: ", str);
   //using normalize() method
   var new_str = str.normalize();
   document.write("<br>The Unicode normalization of the given string: ", new_str);
</script>
</body>
</html>

輸出

上面的程式返回一個包含 Unicode 規範化形式的字串,如下所示:

The given string: Tutorials Point
The Unicode normalization of the given string: Tutorials Point

示例 2

當您將特定的規範化形式“NFKC”作為引數傳遞給此方法時,它會根據該形式修改字串。

以下是 JavaScript String normalize() 方法的另一個示例。我們使用此方法來檢索給定字串“Hello JavaScript”的 Unicode 規範化形式,並且它根據指定的 form 值“NFKC”修改返回的字串。

<html>
<head>
<title>JavaScript String normalize() Method</title>
</head>
<body>
<script>
   const str = "Hello JavaScript";
   document.write("The given string: ", str);
   const form = "NFKC";
   document.write("<br>The form: ", form);
   //using the normalize() method
   const new_str = str.normalize(form);
   document.write("<br>The Unicode normalization of the given string: ", new_str);
</script>
</body>
</html>

輸出

執行上述程式後,它將返回包含 Unicode 規範化形式的字串。

The given string: Hello JavaScript
The form: NFKC
The Unicode normalization of the given string: Hello JavaScript
廣告