繁体   English   中英

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

[英]How to split a string without spaces into an array of words?

所以我在freecodecamp.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"));

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

一种方法是使用Map,然后将名称用作键,将值用作数字。

然后从地图中提取键,对键进行排序,以使最长的字符串排在最前面,并创建一个带有捕获组和交替字符的正则表达式

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

(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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM