合并数字Textarea自动[关闭]

合并数字Textarea自动[关闭]

问题描述:

123456 12-12 3456

How do I automatically convert the text into the Textarea field?

123456 | 12 | 12 | 3456

automatically corrected. How can I do this in Textarea?

  123456 12-12 3456 
  code>  pre> 
 
 

如何自动将文本转换为Textarea字段? p>

  123456 |  12 |  12 |  3456 
  code>  pre> 
 
 

自动更正。 如何在Textarea中执行此操作? p> div>

You can attach a keyup event listener on your textarea and modifying it's content by splitting based on 1 or more non-digit characters and joining them with your desired pipe(|) symbol.

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>

Ok, so as discussed in the comments, for your credit card formatting, you can do something like below:

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) + '
';
              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>

</div>

Use replace:

 

const str = "123456 12-12 3456";
const replaced = str.replace(/\-|\s/g, " | ");
console.log(replaced);

</div>