javascript 逗号分隔URL的正则表达式[重复]

k4ymrczo  于 2023-01-24  发布在  Java
关注(0)|答案(2)|浏览(110)
    • 此问题在此处已有答案**:

Regexp javascript - url match with localhost(7个答案)
12小时前关门了。
截至2小时前,社区正在审查是否重新讨论此问题。
我怎样才能验证逗号分隔的网址,以接受子域,本地主机,并允许空格之前或之后的逗号?这里有一个例子,我希望如何工作:

const regEx = regex; // working regular expression here
console.log(regEx.test('localhost:3000')); // should return true
console.log(regEx.test('https://google.com,https://jeith.com')); // should return true
console.log(regEx.test('subdomain.jeith.com, localhost:3000')); // should return true
console.log(regEx.test('jeith com')); // should return false because of whitespace not near comma
console.log(regEx.test('jeith.com,,localhost:3000')); // should return false because of double comma

我有一个输入请求用逗号分隔的URL。通常对于这样的事情,我会用逗号分隔字符串,并对各个URL执行URL验证,但我在这个项目中无法这样做,因为我正在通过zod进行验证。
这不需要非常严格,也不需要对. com、. net、http://等进行验证。
我是正则表达式的初学者,这是我能得到的最接近这个验证的方法:/^[A-Za-z]+(?:\s*,\s*[A-Za-z]+)*$/。这个表达式缺少的是接受的能力:和.(对于https://和. com)。除此之外,如果出现双逗号或逗号后面有空格,则成功返回false。

0g0grzrc

0g0grzrc1#

看看下面的链接,她已经这样做了,并介绍你一步一步。
RegExr:验证URL:

[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)
jvlzgdj9

jvlzgdj92#

我会采取一个更简单的方法,否则你将不得不写一个复杂的正则表达式,它是极其复杂的验证一个URL。
最好使用内置的URL class

const data = [
  'localhost:3000',
  'https://google.com,https://jeith.com',
  'subdomain.jeith.com, localhost:3000',
  'jeith com',
  'jeith.com,,localhost:3000'
];

for(const item of data) {
  const isValid = item
    .split(',')
    .every(url => {
      try {
         let cleanedUrl = url.trim();
         // URL class requires that the given string includes a protocol
         if(!cleanedUrl.startsWith('http')) {
           cleanedUrl = 'http://' + cleanedUrl;
         }
         if(!cleanedUrl || (/\s+/g).test(cleanedUrl)) {
          return false;
         }
         new URL(cleanedUrl);
         return true;
      } catch(err) {
        return false
      }
    });
    
  console.log(isValid, item);
}

相关问题