我正在创建一个基于网络的会计应用程序,供高中生用作练习。我的 transactionListArray
包含我的 JS 代码中在幕后随机生成的所有交易。 transactionListArray
包含某些字符,其中第一个字符是 date
,为 integer
,其后带有 .
(例如:10.
或 12.
等)。日期后面有一个句子,用于创建会计交易的措辞、帐户名称、付款方式和各种其他内容。
基本交易会产生以下输出:
27. Trusted Traders purchased trading stock to the value of R108756.
我已经到处寻找,但仍然找不到适合我喜欢的解决方案。
我几天来遇到的问题是试图弄清楚如何使用正则表达式 match
关键字返回字符串。当我尝试将 currentString
与 nextString
(数组中的下一个值)匹配时,问题就出现了。
见下文:
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.';
然后,当 currentString
和 NextString
相等时,我想替换 nextString
。
像这样:
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);
最佳答案
如果你想改变原始数组,你可以这样做:
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);
关于javascript - 替换字符串数组中的正则表达式字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54146203/