2 回答

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超3個(gè)贊
您可以在文本區(qū)域上附加一個(gè)keyup事件偵聽器,并通過基于1個(gè)或多個(gè)非數(shù)字字符進(jìn)行拆分并將其與所需的pipe(|)符號(hào)連接起來來修改其內(nèi)容。
document.getElementById('some_id').addEventListener('keyup',function(){
var content = this.value.split(/[^\d]+/);
this.value = content.join(" | ");
});
<textarea rows='10' cols='50' id='some_id'>
</textarea>
好的,正如評(píng)論中所討論的那樣,對(duì)于信用卡格式,您可以執(zhí)行以下操作:
document.getElementById('some_id').addEventListener('keyup',function(){
var content = this.value;
var new_content = '';
var temp_content = '';
var current_length = 0;
for(var i=0;i<content.length;++i){
if('0123456789'.indexOf(content.charAt(i)) != -1){
temp_content += content.charAt(i);
current_length++;
}
if(current_length === 25){
new_content += insertPipeForCreditCardFormat(temp_content) + '\n';
temp_content = '';
current_length = 0;
}
}
this.value = new_content + temp_content;
});
function insertPipeForCreditCardFormat(credit_card){
var pipe_indices = new Set([16,18,22]);
var card_format = '';
for(var i=0;i<credit_card.length;++i){
if(pipe_indices.has(i)){
card_format += '|';
}
card_format += credit_card.charAt(i);
}
return card_format;
}
<textarea id='some_id' rows='10' cols='50'></textarea>

TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
用途replace:
const str = "123456 12-12 3456";
const replaced = str.replace(/\-|\s/g, " | ");
console.log(replaced);
- 2 回答
- 0 關(guān)注
- 151 瀏覽
添加回答
舉報(bào)