我希望在 JavaScript 中洗掉 ':->' 之后的任何值 例如,如果 'Packet:->3',我想將“Packet:->”存盤在變數中,這樣我就可以在看到 if 陳述句之前使用它以下。幾乎我希望洗掉“>”之后的任何數字
我正在嘗試以下方法,但運氣不佳。
NTEremoved = NTE.indexOf(':->');
這樣做的最佳方法是什么?
if(NTE == 'Packet:->' || NTE == 'Serving:->' || NTE == 'Can/Carton/Bottle:->'){
}
uj5u.com熱心網友回復:
我會做這樣的事情,以照顧邊緣情況(假設你不關心第一個之后會發生什么:->:
let texts = ["Packet:->11", "Cat:->22", "Packet:->:->:->44"];
for (let text of texts) {
console.log(text.replace(/(:->).*$/, "$1"))
}
uj5u.com熱心網友回復:
字串拆分。
const testStr1 = "Packet:->3";
const testStr2 = "BlahBlahBlah278:->Hello hello this is cool";
const result1 = testStr1.split(":->")[0] ":->"; // split "splits" the string into an array based on the delimiter ":->"; the second part would be 3
const result2 = testStr2.split(":->")[0] ":->";
console.log(result1);
console.log(result2);
檔案。
uj5u.com熱心網友回復:
既然您提到您indexOf之前曾嘗試使用但未能做到這一點,我將為您提供一種結合使用indexOf和String.splice
let string = "Serving:->3"
//Indexof return the first index of an element so you have to add 3 (the length of ":->"
let newstring = string.slice(0,string.indexOf(":->") 3)
console.log(newstring)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/405313.html
標籤:
上一篇:如何只回傳數值?
下一篇:HTML加載,但腳本不運行
