如何将没有空格的字符串拆分成单词数组?

时间:2019-01-30 10:01:02

标签: javascript regex

因此,我正在freefreecamp.org上通过编写电话检查程序的算法来练习javascript。当仅提供的电话号码是一串数字时,我成功检查了它。现在,我被卡住了,并且不知道如何检查提供的电话号码中是否包含诸如“ sixnineone”之类的单词。因此,我想将其拆分为“六个九个一”或将其与数字对象数组转换为“ 691”。

这是问题所在:

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator

我试图通过网站获得一些提示,但是它们只能用我不太理解的正则表达式解决问题。

这是我所做的:

    function telephoneCheck(str) {
    let phoneNum = str.toLowerCase().replace(/[^1-9a-z]/g, "");
    let numbers = [
        {0: "o"},
        {1: "one"},
        {2: "two"},
        {3: "tree"},
        {4: "four"},
        {5: "five"},
        {6: "six"},
        {7: "seven"},
        {8: "eight"},
        {9: "nine"}
    ];

    if (phoneNum.match(/[1-9]/)) {
        phoneNum = phoneNum.split('')

        if (phoneNum.length === 10) {
            phoneNum.unshift(1);
        }

        for (let i = 0; i < phoneNum.length; i++) {
            phoneNum[i] = Number(phoneNum[i]);
        }

        if (phoneNum.length === 11 && phoneNum[0] === 1) {
            return true;
        } else {
            return false;
        }

    }

    if (phoneNum.match(/[a-z]/)) {
        console.log(phoneNum);
    }
}

console.log(telephoneCheck("sixone"));

在解决问题的过程中,据说唯一的解决方案就是他们的解决方案,但是如果我认为正确,那么可能还会有另一种解决方案。

1 个答案:

答案 0 :(得分:0)

一种方法可能是使用Map并将名称用作键,将值用作数字。

然后从地图中提取键,对它们进行排序,以使最长的字符串排在最前面,并创建一个带有捕获组和alternation

的正则表达式

正则表达式最终看起来像:

(three|seven|eight|four|five|nine|one|two|six|o)

然后使用此正则表达式分割字符串。在不包含键的情况下映射所有项以除去所有非数字,并从数组中除去所有空值。

最后使用键从地图上获取值。

let map = new Map([
  ["o", 0],
  ["one", 1],
  ["two", 2],
  ["three", 3],
  ["four", 4],
  ["five", 5],
  ["six", 6],
  ["seven", 7],
  ["eight", 8],
  ["nine", 9]
]);
let regex = new RegExp("(" + [...map.keys()]
  .sort((a, b) => b.length - a.length)
  .join('|') + ")");

let strings = [
  "69ooooneotwonine",
  "o",
  "testninetest",
  "10001",
  "7xxxxxxx6fivetimesfifefofourt",
  "test"

].map(s =>
  s.split(regex)
  .map(x => !map.has(x) ? x.replace(/\D+/, '') : x)
  .filter(Boolean)
  .map(x => map.has(x) ? map.get(x) : x)
  .join(''));

console.log(strings);

相关问题