我有一個div,我需要除去最後四位以外的所有字符。我目前正在使用replaceWith,但它取代了整個事情。JQuery替換除最後四位數以外的CC號
這裏就是我有
<div class="field-name-field-credit-card">1111111111111111</div>
$(".field-name-field-credit-card").replaceWith("xxxx xxxx xxxx xxxx");
和我的結果
<div class="field-name-field-credit-card">xxxx xxxx xxxx xxxx</div>
但我想它是:
<div class="field-name-field-credit-card">xxxx xxxx xxxx 1111</div>
我剛剛注意到,在這個jQuery是不好的,因爲你使用'.field-name-field-credit-card',一個類名,就好像它是一個唯一的ID。如果您碰巧嘗試做兩個信用卡領域,此代碼會遇到問題。這會比$(「。field-name-field-credit-card」)好得多。text(function(_,txt){return txt.replace(/.*(\ d {4})$/「xxxx xxxx xxxx $ 1」);});'(當然添加了空格),因爲這將正確處理任意數量的字段。請參閱[文檔](http://api.jquery.com/text/#text-function) –
感謝修復,@NiettheDarkAbsol。你的更強大。 –
至少有一個非常糟糕的理由在JavaScript中做到這一點。如果在單頁結賬嚮導中顯示訂單確認作爲最後一步,並且cc編號(剛輸入到客戶端的表單字段中)尚未發送到服務器,然後通過javascript顯示一個屏蔽的cc數是正確的方法。 – simmer