gpt4 book ai didi

javascript - 创建正则表达式以将每个单词与 分开。 (点)

转载 作者:行者123 更新时间:2023-11-28 03:11:27 29 4
gpt4 key购买 nike

我正在尝试创建一个正则表达式来将 JavaScript 中的每个单词与 .(点)分开。

function myFunction() {
var url = "in.k1.k2.k3.k4.com"
var result
var match
if (match = url.match(/^[^\.]+\.(.+\..+)$/)) {
console.log(match);
}
}

实际结果是:

match[0] : in.k1.k2.k3.k4.com
match[1] : k1.k2.k3.k4.com

预期结果是:

match[0] : in.k1.k2.k3.k4.com
match[1] : k1.k2.k3.k4.com
match[2] : k2.k3.k4.com
match[3] : k3.k4.com
match[4] : k4.com

请帮助我创建完美的正则表达式。

最佳答案

在这种情况下,使用正则表达式可能不是最佳选择。您可以简单地在 . 处拆分字符串,然后在需要时将它们连接起来。

function recursivelySplitText(arrayOfString, output) {
// check if the output is set, otherwise create it.
if(!output) {
output = [];
}
// we add the current value to the output
output.push(arrayOfString.join('.'));
// we remove the first element of the array
arrayOfString.splice(0, 1);
// if we just have one element left in the array ( com ) we return the array
// otherwise, we call the function again with the newly splitted array.
return arrayOfString.length === 1 ? output : recursivelySplitText(arrayOfString, output);
}

const text = 'in.k1.k2.k3.k4.com';
// we need to split it first to have an array of string rather than a string.
console.log(recursivelySplitText(text.split('.')));

这里我使用递归,因为它很有趣,但它不是获得相同结果的唯一方法。

关于javascript - 创建正则表达式以将每个单词与 分开。 (点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60078041/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com