亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

String.Replace() 的小問題

String.Replace() 的小問題

肥皂起泡泡 2021-10-21 15:01:30
還不太精通 JS,我遇到了一個奇怪的問題,它似乎.replace() 應該可以工作,但實際上卻沒有。我只是想獲取一個包含文本 + 數字的字符串(來自元素 ID),用 RegEx 模式替換數字,然后用原始文本 + 新數字替換該 ID 中的原始文本。我的 HTML 示例:<html>  <body>    <p>Click the button to replace "Movies: 12344" with "Movies: 54321" in the paragraph below:</p>    <p id="demo">Movies: 1234!</p>    <button onclick="myFunction()">Try it</button>  </body></html>我的JS:function myFunction() {  // Get all the text in #id=demo  var str = document.getElementById("demo");   // RegEx pattern to find ": <some digits>"  var pat = /\:\s?\d*/;  // Replace the digits  var res = str.replace(pat, ': 54321');  // Doesn't work (as a test) ...  //res = " hi"  // Replace the text in id=demo with original text + new digits.  str.innerHTML = res;  // Doesn't work (as a test) ...  //document.getElementById("demo").innerHTML = res;}目前,點擊頁面中的按鈕后,什么也沒有發生。這也可能有點幫助:https : //codepen.io/stardogg/pen/aboREmL
查看完整描述

3 回答

?
收到一只叮咚

TA貢獻1821條經驗 獲得超5個贊

與您在innerHTML函數的最后一行設置相同的方式,innerHTML也是您應該應用的replace內容:


function myFunction() {

  var str = document.getElementById("demo");


  var pat = /\:\s?\d*/;


  var res = str.innerHTML.replace(pat, ': 54321');


  str.innerHTML = res;

}

<p>Click the button to replace "Movies: 12344" with "Movies: 54321" in the paragraph below:</p>


<p id="demo">Movies: 1234!</p>


<button onclick="myFunction()">Try it</button>


查看完整回答
反對 回復 2021-10-21
?
四季花海

TA貢獻1811條經驗 獲得超5個贊

您的str變量不等于元素內的文本節點,而是元素本身。要使str元素內的文本相等,請嘗試以下操作。

var str = document.getElementById("demo").innerText;


查看完整回答
反對 回復 2021-10-21
?
江戶川亂折騰

TA貢獻1851條經驗 獲得超5個贊

您需要在替換之前從元素中提取文本。


//Replace the digits

var res = str.innerHTML.replace(pat, ': 54321');


查看完整回答
反對 回復 2021-10-21
  • 3 回答
  • 0 關注
  • 218 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號