如何在NodeJS中查找中英文字符?

问题描述 投票:0回答:1

我有一个包含中英文字符的字符串,我想将该字符串拆分为各个中英文字符。

以下是一些示例:

  1. 你好
  2. 你好你好你好

[This page教了如何检测汉字,但是在分割字符串时却不起作用。

提前感谢

javascript node.js string chinese-locale
1个回答
0
投票

您可以在每次出现“中文”字符时,在每次出现空格时都将字符串拆分,如下所示:

  let chiStr = "你好 你好 hello"
  chiStr.split(' ')//splitting the string at every occurrence of a space
  //expected result: ["你好", "你好", "hello"]

  const REGEX_CHINESE = /[\u4e00-\u9fff]|[\u3400-\u4dbf]|[\u{20000}-\u{2a6df}]|[\u{2a700}-\u{2b73f}]|[\u{2b740}-\u{2b81f}]|[\u{2b820}-\u{2ceaf}]|[\uf900-\ufaff]|[\u3300-\u33ff]|[\ufe30-\ufe4f]|[\uf900-\ufaff]|[\u{2f800}-\u{2fa1f}]/u;
  const hasJapanese = (str) => REGEX_CHINESE.test(str);

  chiStr.split(REGEX_CHINESE) splitting the string at every occurrence of a 'chinese' character
  //expected result: ["你", "好", "你", "好", " hello"]

另一个好的方法是将中文单词和英文单词过滤成单独的数组:

const REGEX_CHINESE = /[\u4e00-\u9fff]|[\u3400-\u4dbf]|[\u{20000}-\u{2a6df}]|[\u{2a700}-\u{2b73f}]|[\u{2b740}-\u{2b81f}]|[\u{2b820}-\u{2ceaf}]|[\uf900-\ufaff]|[\u3300-\u33ff]|[\ufe30-\ufe4f]|[\uf900-\ufaff]|[\u{2f800}-\u{2fa1f}]/u;
const hasJapanese = (str) => REGEX_CHINESE.test(str);

const seperateWords = (str)=>{
   let newStr = str.split(' ')
   let chiWords = newStr.filter((string)=>REGEX_CHINESE.test(string))//All chinnese words
   let engWords = newStr.filter((string)=>!REGEX_CHINESE.test(string)) //All english words
   let arrayOfDiffWords = [chiWords, engWords]
   return arrayOfDiffWords
}
console.log(seperateWords("你好 你好 hello")) //test
© www.soinside.com 2019 - 2024. All rights reserved.