kevin_marcus
kevin_marcus

Reputation: 277

How to insert characters in between in jquery?

I have this data from the database 12345123412 but in my page I need to display it as 12345-1234-12. Any ideas on how to handle this? I'm trying to do the .split()

Upvotes: 0

Views: 224

Answers (3)

hackdotslashdotkill
hackdotslashdotkill

Reputation: 40

Simplified approach...with jquery..

Get 3 substrings then format..

Var id = 12345123412
Function getId(id){     
    Var sub1 =id.substring(0,5);
    Var sub2 =id.substring(5,9);
    Var sub3 =id.substring(9,11);
    Var id = sub1 +"-"+sub2+"-"+sub3;
    Return id;
}

getId();

Upvotes: 1

A.D.
A.D.

Reputation: 2372

There so many ways to do this but you can use a simple function to convert a number to a dass separated number as follows.

 //This function returns the result as per your question.
 function commaSeparateNumber(val){   
    var regex =new  RegExp("(\\d{5})(\\d+)");
    var valEdit = val.toString().replace(regex, '$1'+'-');
    var valleft = val.toString().replace(regex, '$2');
    var regex =new  RegExp("(\\d{4})(\\d+)");
    val = valleft.toString().replace(regex, '$1'+'-'+'$2');    
    return valEdit+val;
 }
 console.log(commaSeparateNumber(12345123412));

//This function work for change at every 4 digit insertion
function commaSeparateNumber(val){
    while (/(\d{4})(\d+)/.test(val.toString())){
      val = val.toString().replace(/(\d{4})(\d+)/, '$1'+'-'+'$2');
    }
    return val;
  }
  console.log(commaSeparateNumber(12345123412));

Upvotes: 1

Sara M
Sara M

Reputation: 455

Assuming the string is always going to be formatted the exact same way, there's no reason to use jQuery for this:

var str = '12345123412';

var formatted = str.slice(0, 5) + '-' + str.slice(5, 9) + '-' + str.slice(9);
  //=> 12345-1234-12

Upvotes: 5

Related Questions