for (let i = 0; i < ans.length; i ) {
ans = ans.replace(' ', ' ');
ans = ans.replace(' ', ' ');
ans = ans.replace(' ', ' ');
//here ans is a value of an input.
}
為什么在完成程序之前停止?
uj5u.com熱心網友回復:
您在回圈的每次迭代中執行相同的操作,因此回圈在此代碼塊中是多余的。如果您打算替換所有出現的內容,則使用正則運算式替換會更好:
ans = ans.replace(/ /g, ' ');
ans = ans.replace(/ /g, ' ');
ans = ans.replace(/\ \ /g, ' ');
如果您只針對現代瀏覽器,則可以replaceAll改用:
ans = ans.replaceAll(' ', ' ');
ans = ans.replaceAll(' ', ' ');
ans = ans.replaceAll(' ', ' ');
uj5u.com熱心網友回復:
好吧,根據代碼,我看到無論連續有多少個空格,您都想擺脫空格,因此我建議使用正則運算式:
let ans = "im an input here so you can see the stuff"
ans = ans.replace(/\s /g , ' '); \* im an input here so you can see the stuff *\
就像Wais Kamal Answer上所說的那樣,您也可以將replaceAll()其用于不同的情況
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/375413.html
標籤:javascript for循环 str替换
