我的应用程序中有一些单行文本字段,它以这种格式(3年4个月零4天)存储数据。现在,我只想从字段中检索整数部分,并希望给出if条件来检查某些条件。
有人可以帮助我实现这一目标吗?
我的应用程序中有一些单行文本字段,它以这种格式(3年4个月零4天)存储数据。现在,我只想从字段中检索整数部分,并希望给出if条件来检查某些条件。
有人可以帮助我实现这一目标吗?
假设您提供给我们的格式是准确的,那么您可以尝试这样的方法。
let exampleString = "3 years,4 Months and 4 days";
const extractYMD = (input) => {
const stringArray = input.split(' ');
//split the string on every space
//it will create an array that looks like this
//["3","years,","4","Months","and","days"]
//then you can use the index to find your ints
const years = parseInt(stringArray[0])
const months = parseInt(stringArray[2])
const days = parseInt(stringArray[5])
//using parseInt because values inside the array are still strings
//don't need to assign to variables but did it for clarity
if(years <= 3){
console.log('example condition')
//do something here
}
console.log(years,months,days)
//logging to console so you can see output
return [years,days];
// return the values if you need them for something
};
extractYMD(exampleString);
也可以选择使用正则表达式,但是有风险您将获得324这样的输出,并且您不知道它是32年零4天还是3个月零24天。 You can learn about and test regex here。
请记住,上面的功能非常依赖于您所描述的格式。任何偏差都会引起问题。理想情况下,您应在将数据转换为此字符串格式之前设法检索数据。但是我们需要查看您的更多代码以了解您为何处于这种情况。