如何基于每个四个逗号将字符串拆分为数组

如何基于每个四个逗号将字符串拆分为数组

本文介绍了如何基于每个四个逗号将字符串拆分为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正尝试根据逗号数量将字符串拆分为数组,该怎么办?说我的弦是这样的;

so I'm trying to split a string into an array based on the amount of commas, how do I do that? Say my string is as such;

var string = "abc, def, ghi, jkl, mno, pqr, stu, vwx, yza";

我如何分割它以便它返回;

How can i split it so that it returns;

var array = ["abc, def, ghi, jkl,", "mno, pqr, stu, vwx,", "yza"]

这甚至有可能吗?

现在我正在使用var array = string.split(', ');

但是这会基于每个逗号将字符串添加到数组中.

But this adds the strings into the array based on every single comma.

任何帮助将不胜感激!

Any help would be appreciated!

推荐答案

我将使用.match而不是split-匹配(非逗号,后跟逗号或字符串结尾)4次:

I'd use .match instead of split - match (non commas, followed by a comma or the end of the string) 4 times:

var string = "abc, def, ghi, jkl, mno, pqr, stu, vwx, yza";
const result = string.match(/(?:[^,]+(?:,|$)){1,4}/g);
console.log(result);
  • (?:[^,]+(?:,|$)){1,4}-重复1至4次:
    • [^,]+-非逗号字符
    • (?:,|$)-逗号或字符串的结尾
    • (?:[^,]+(?:,|$)){1,4} - Repeat, 1 to 4 times:
      • [^,]+ - Non comma characters
      • (?:,|$) - Either a comma, or the end of the string

      如果要确保第一个字符不是空格,请在开头搜索\S(非空格字符):

      If you want to make sure the first character is not whitespace, lookahead for \S (a non-whitespace character) at the beginning:

      var string = "abc, def, ghi, jkl, mno, pqr, stu, vwx, yza";
      const result = string.match(/(?=\S)(?:[^,]+(?:,|$)){1,4}/g);
      console.log(result);

      这篇关于如何基于每个四个逗号将字符串拆分为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 18:27