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

How to find chinese and english character in NodeJS?

我有一个包含中英文字符的字符串,我想将字符串拆分成单独的中英文字符。

这里有一些例子:

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

This page 教如何检测汉字,但在拆分字符串时不起作用。

提前致谢

您可以在每次出现 'Chinese' 字符时在每次出现 space 时拆分字符串,如下所示:

  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