Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Chinese Character Pinyin Conversion in Frontend Applications

Tech 2

pinyin-pro is a JavaScript library that enables pinyin conversion for Chinese characters directly in frontend environments. It supports various output formats, including pinyin strings, initials, finals, tones, and first letters, along with features like surname mode and custom pinyin definitions.

Key Features

  • Convert Chinese characters, words, or sentences to pinyin
  • Extract initials, finals, or tones from characters
  • Retrieve the first letter of pinyin
  • Handle polyphonic characters with multiple pinyin outputs
  • Support for surname-specific pinyin modes
  • Customizable pinyin mappings
  • Output as strings or arrays
  • Pinyin text matching capabilities

Installation

Install via npm or yarn:

npm install pinyin-pro
# or
yarn add pinyin-pro

Import Methods

Browser Script Tag

<script src="https://cdn.jsdelivr.net/gh/zh-lx/pinyin-pro@latest/dist/pinyin-pro.js"></script>
<script>
  const { pinyin } = pinyinPro;
  console.log(pinyin('汉语拼音')); // Outputs: 'hàn yǔ pīn yīn'
</script>

ES Module

import { pinyin } from 'pinyin-pro';
console.log(pinyin('汉语拼音')); // Outputs: 'hàn yǔ pīn yīn'

CommonJS (Node.js)

const { pinyin } = require('pinyin-pro');
console.log(pinyin('汉语拼音')); // Outputs: 'hàn yǔ pīn yīn'

Dynamic Import

import('pinyin-pro').then(({ pinyin }) => {
  console.log(pinyin('汉语拼音')); // Outputs: 'hàn yǔ pīn yīn'
});

Parameters

The pinyin function accepts two arguments: pinyin(inputText, configuration).

  • inputText: Reuqired. A string containing Chinese characters to convert.
  • configuration: Optional. An object to customize output behavior with the following properties:
Parameter Description Type Values Default
pattern Output type (pinyin/initial/final/num/first) string pinyin, initial, final, num, first pinyin
toneType Tone representation (symbol/num/none) string symbol, num, none symbol
type Output format (string/array) string string, array string
multiple Output all pinyin for polyphonic characters (only for single-character strings) boolean true, false false
mode Lookup mode (normal/surname) string normal, surname normal
removeNonZh Filter non-Chinese characters from input boolean true, false false
nonZh Handling of non-Chinese characters (spaced/consecutive/removed) string spaced, consecutive, removed spaced
v Replace ü with v boolean true, false false

Real-time Pinyin Display with HTML Ruby Annotations

HTML provides <ruby>, <rp>, and <rt> elements for phonetic annotations, ideal for displaying pinyin above Chinese text.

Example in supporting browsers:

<ruby>
  雷猴<rp>(</rp><rt>leihou</rt><rp>)</rp>
</ruby>

In non-supporting browsers, the content inside <rp> tags is displayed as fallback.

Implementation Example: Live Pinyin Conversion

Create an input field that dynamically shows pinyin annotations:

<p>
  <ruby>
    <span id="displayText"></span>
    <rp>(</rp>
    <rt id="pinyinOutput"></rt>
    <rp>)</rp>
  </ruby>
</p>

<input type="text" id="userInput" oninput="updatePinyin(this)">

<script src="https://cdn.jsdelivr.net/gh/zh-lx/pinyin-pro@latest/dist/pinyin-pro.js"></script>
<script>
  const { pinyin } = pinyinPro;
  const textElement = document.getElementById('displayText');
  const pinyinElement = document.getElementById('pinyinOutput');
  
  let debounceTimer = null;
  
  function updatePinyin(inputField) {
    if (debounceTimer) clearTimeout(debounceTimer);
    
    debounceTimer = setTimeout(() => {
      const pinyinResult = pinyin(inputField.value);
      textElement.textContent = inputField.value;
      pinyinElement.textContent = pinyinResult;
    }, 200);
  }
</script>

This setup allows users to type Chinese characters and see their pinyin annotations update in real-time with debouncing to optimize performance.

Tags: frontend

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.