英文:
How To Split 0 Day 15 Hour 1 Min 0 Sec and assign it in different variable in java script?
问题
var time = "0 Day 15 Hour 1 Min 0 Sec";
// 从字符串中提取数字并赋值给变量
var day = parseInt(time.match(/\d+(?=\sDay)/)[0]);
var hour = parseInt(time.match(/\d+(?=\sHour)/)[0]);
var min = parseInt(time.match(/\d+(?=\sMin)/)[0]);
var sec = parseInt(time.match(/\d+(?=\sSec)/)[0]);
英文:
I have a string like this:
var time ="0 Day 15 Hour 1 Min 0 Sec";
How can I extract the numbers in the string into variables like below?
var day=0;
var hour=15;
var min=1;
var sec=0;
答案1
得分: 4
你可以使用全局正则表达式来匹配数字,然后立即解构以将这4个匹配项放入4个变量中:
var time = "0 Day 15 Hour 1 Min 0 Sec";
const [day, hour, min, sec] = time.match(/\d+/g);
console.log(day);
console.log(hour);
console.log(min);
console.log(sec);
请注意,以上是代码示例,用于提取时间中的数字并将其存储在相应的变量中。
英文:
You can use a global regular expression to match digits, then destructure immediately to put the 4 matches into 4 variables:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var time ="0 Day 15 Hour 1 Min 0 Sec";
const [day, hour, min, sec] = time.match(/\d+/g);
console.log(day);
console.log(hour);
console.log(min);
console.log(sec);
<!-- end snippet -->
答案2
得分: 1
以下是代码段的翻译部分:
var time = "0 天 15 小时 1 分钟 0 秒";
var numericValue = [];
var textKey = [];
var result = {};
time.split(" ").map((value, index) => {
return (
(index + 1) % 2 == 0 ?
textKey.push(value.toLowerCase())
: numericValue.push(Number(value))
)
});
for (let i = 0; i < textKey.length; i++) {
result[textKey[i]] = numericValue[i]
}
console.log(result);
console.log(result.day);
请注意,我已经将代码中的HTML实体编码(例如<
和>
)还原为正常的JavaScript代码。
英文:
check out the code snippet:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var time ="0 Day 15 Hour 1 Min 0 Sec";
var numericValue=[];
var textKey=[];
var result={};
time.split(" ").map((value,index)=> {
return (
(index+1)%2 == 0 ?
textKey.push(value.toLowerCase())
: numericValue.push(Number(value))
)
});
for(let i=0;i<textKey.length;i++){
result[textKey[i]]=numericValue[i]
}
console.log(result);
console.log(result.day);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论