2 回答
TA贡献1798条经验 获得超3个赞
您可以在文本区域上附加一个keyup事件侦听器,并通过基于1个或多个非数字字符进行拆分并将其与所需的pipe(|)符号连接起来来修改其内容。
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>
好的,正如评论中所讨论的那样,对于信用卡格式,您可以执行以下操作:
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贡献1809条经验 获得超8个赞
用途replace:
const str = "123456 12-12 3456";
const replaced = str.replace(/\-|\s/g, " | ");
console.log(replaced);
- 2 回答
- 0 关注
- 128 浏览
添加回答
举报