首页 > 解决方案 > 替换字符串数组中的正则表达式字符串

问题描述

我正在为高中生创建一个基于网络的会计应用程序以用作练习。我的transactionListArray包含在我的 JS 代码中在幕后随机生成的所有交易。包含某些字符,transactionListArray包括第一个字符,即dateas an integer.后面跟着它(例如:10.12.等)。在日期之后有一个句子,它创建了会计交易的措辞、账户名称、付款方式和其他各种内容。

一个基本的交易产生这个输出:

27. Trusted Traders purchased trading stock to the value of R108756.

我到处寻找,但仍然找不到适合我喜欢的解决方案。

几天来我一直面临的问题是试图弄清楚如何使用正则表达式match关键字返回一个字符串。当我尝试将其currentStringnextString数组中的下一个值匹配时,问题就出现了。

见下文:

let length = array.length-1;
for (let i = 0; i < length; i++) {
    let regex = /d+\./; // this returns the value of the first number(the date) and the "." symbol
    let currentString = array[i];
    let nextString = array[i+1];
    let currentDate = currentString.match(regex); // errors
    let nextDate = nextString.match(regex); // errors
};

以上不会产生我期望的输出。currentDate和行中所述的错误nextDate说:

TypeError: Cannot read property '0' of null

这个问题令人困惑,因为我检查了当前迭代和下一次迭代值,但它没有返回我的正则表达式字符串。

例如,我期待这个:

currentDate[0] = '11.';
nextDate[0] = '10.';

然后我想替换nextStringcurrentStringNextString相等时。像这样:

let replaceDateWithBlankSpace = (array) => {
    let length = array.length-1;
    for (let i = 0; i < length; i++) {
        let regex = /d+\./;
        let currentString = array[i];
        let nextString = array[i+1];
        let currentDate = currentString.match(regex); // TypeError: Cannot read property '0' of null
        let nextDate = nextString.match(regex); // TypeError: Cannot read property '0' of null
        if (currentDate[0] === nextDate[0]) { // checking if both are equal 
            nextString.replace(regex, "   "); // and then replacing the string regex that was calculated with blank space at array[i+1]
        }
    }
};

我在我的transactionListArray

replaceDateWithBlankSpace(transactionListArray);

标签: javascript

解决方案


如果你想改变原始数组,你可以这样做:

const arr = [
    '25. Trusted Traders purchased trading stock to the value of R138756.',
    '26. Trusted Traders purchased trading stock to the value of R432756.',
    '26. Trusted Traders purchased trading stock to the value of R108756.',
    '28. Trusted Traders purchased trading stock to the value of R333756.',
];

const replaceDateWithBlankSpace = array => {
    const length = array.length - 1;
    const regex = /^\d+\./;

    for (let i = 0; i < length; i++) {
        const currentString = array[i];
        const nextString = array[i + 1];
        const currentDate = currentString.match(regex);
        const nextDate = nextString.match(regex);

        if (currentDate && nextDate && currentDate[0] === nextDate[0]) {
            array[i + 1] = array[i + 1].replace(regex, '   ');
        }
    }
};

replaceDateWithBlankSpace(arr);

console.log(arr);


推荐阅读