不能使regex工作删除第一个空格字符

时间:2021-09-04 20:12:26

I have the following div:

我有以下的分类:

<div data-test="([1] Hello World), ([2] Foo Bar)"></div>

Now what I am trying to do is to find the cleanest way to break the string into the following pieces:

现在我要做的是找到最干净的方法把绳子分成以下几部分:

array ["1", "Hello World", "2", "Foo Bar"];

数组["1","Hello World", "2", "Foo Bar"];

How can I achieve this the proper and fast way?

我如何才能以正确、快速的方式实现这一目标?

I managed to get close but my solution seems somewhat ugly and doesnt work as expected.

我设法接近了目标,但我的解决方案似乎有些难看,而且没有达到预期的效果。

var el = document.getElementsByTagName("div")[0];
    data = el.getAttribute('data-test');
    list = data.replace(/[([,]/g, '').split(/[\]\)]/);

for(str of list) {
    str = str.trim();
}

I still get the spaces at the start of each string. I dont really want to use trim or anything similar. I tried to add a whitespace character to my regex s/ but that was a bad idea too.

我仍然得到每个字符串开头的空格。我真的不想用修剪之类的东西。我试图在regex s/中添加空格字符,但这也不是一个好主意。

3 个解决方案

#1


2  

The below function should work.

下面的函数应该有效。

function strToArr(str) {
    var arr = [];
    var parts = str.split(', ');
    parts.forEach(part => {
        var digit = part.match(/(\d+)/g)[0];
        var string = part.match(/(\b[a-zA-Z\s]+)/g)[0];
        arr.push(digit, string);
    });
    return arr;
}

#2


1  

var text = '([1] Hello World), ([2] Foo Bar)';

var textReplaced = text.replace(/\(\[([^\]])\]\s([^)]+)\)/g, '$1, $2');

var array = textReplaced.split(', ');

console.log(array);

Without any cycle.

没有任何周期。

#3


0  

You can try the following regular expression:

你可以试试下面的正则表达式:

list = data.replace(/^\(\[|\)$/g, '').split(/\] |\), \(\[|\] /);

Two steps:

两个步骤:

  1. remove the heading "(["and tailing ")"
  2. 去掉标题"(["和尾")"
  3. split the string into the parts you want with the delimiter symbols
  4. 使用分隔符符号将字符串分割成需要的部分

Suppose the format of the string is fixed.

假设字符串的格式是固定的。

#1


2  

The below function should work.

下面的函数应该有效。

function strToArr(str) {
    var arr = [];
    var parts = str.split(', ');
    parts.forEach(part => {
        var digit = part.match(/(\d+)/g)[0];
        var string = part.match(/(\b[a-zA-Z\s]+)/g)[0];
        arr.push(digit, string);
    });
    return arr;
}

#2


1  

var text = '([1] Hello World), ([2] Foo Bar)';

var textReplaced = text.replace(/\(\[([^\]])\]\s([^)]+)\)/g, '$1, $2');

var array = textReplaced.split(', ');

console.log(array);

Without any cycle.

没有任何周期。

#3


0  

You can try the following regular expression:

你可以试试下面的正则表达式:

list = data.replace(/^\(\[|\)$/g, '').split(/\] |\), \(\[|\] /);

Two steps:

两个步骤:

  1. remove the heading "(["and tailing ")"
  2. 去掉标题"(["和尾")"
  3. split the string into the parts you want with the delimiter symbols
  4. 使用分隔符符号将字符串分割成需要的部分

Suppose the format of the string is fixed.

假设字符串的格式是固定的。