How to Insert a Character After Every N Characters in JavaScript

How can I insert a character after every n characters in javascript?

function chunk(str, n) {
var ret = [];
var i;
var len;

for(i = 0, len = str.length; i < len; i += n) {
ret.push(str.substr(i, n))
}

return ret
};

chunk("The quick brown fox jumps over the lazy dogs.", 5).join('$');
// "The q$uick $brown$ fox $jumps$ over$ the $lazy $dogs."

Insert character after every nth character

var num = 1215464565; 
var newNum = num.toString().match(/.{2}/g).join('-');
console.log(newNum);

jsFiddle example

JavaScript: Insert a character after every N characters

You could use a regex replacement:

var str = "34v188d9cefa401f988563fb153xy04b";
var output = str.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, "$1-$2-$3-$4-$5");
console.log(output);

Javascript: Insert a character in a string every nth

If you are trying to format a number, instead of rolling your own solution, you could rely on JavaScript's built-in features:

var myNumber = '1000000';var formattedNumber = Number(myNumber).toLocaleString();
console.log(formattedNumber); // "1,000,000"

Insert a character after every n characters but only for the first x occurrences

What about .replace(/(.{3})(.{3})(.{3})/,'$1-$2-$3-')?

Javascript function to ensure string has space every n characters

Replace . with [0-9] to match digits only and use a negative lookahead (?!...) where ... is your char:

function myfunc(s, ch, limit) {  var rx = new RegExp(    "[0-9]{"+limit+"}"+ // Match a digit, limit times    "(?!"+  // Only match if, immediately to the right, there is no    ch.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')+ // delimiting char (escaped)    "|$)", // or end of string    "g"); // Global modifier, replace all occurrences  return s.replace(rx, "$&" + ch); // Replace with the match itself + delimiting char}console.log(myfunc('01234567890', ' ', 5))    // = '01234 56789 0'console.log(myfunc('01 234567890', ' ', 5))   // = '01 23456 7890'console.log(myfunc('01 234 56789 0', ' ', 5)) // = '01 234 56789 0'

How to insert a character every n characters from end of string

You may use

gsub('(?=(?:.{5})+$)', ":", text, perl = TRUE)
## => [1] "M:y Ver:y Ent:husia:stic :Mothe:r Jus:t Ser:ved U:s Noo:dles!"

See the regex demo

The (?=(?:.{5})+$) pattern matches any location inside the string that is followed with any 5 chars (other than line break chars) 1 or more times up to the end of the string.

If the input string can contain line breaks you need to add (?s) at the start of the pattern (since . in PCRE regex does not match line breaks by default):

'(?s)(?=(?:.{5})+$)'

REGEX insert character every n-times starting at the end of string

Try something like:

numberString.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.")

Just be sure that numberString is indeed a string, or convert it with .toString().

Explanation:
This is very tricky; it will match every digit (\d) that comes before a group of three digits \d{3} or this group repeated more than once (\d{3])+ (so every multiple of three) that is not followed by another digit !\d

It uses positive lookahead (?=) and negative lookahead (?!) in order to match or exclude parts of the strings without including them into the match results.

Then it replaces the first matching group (the digit) with itself (using the backreference $1) followed by a dot.

put dash after every n character during input from keyboard and edit exact number

The actual problem is, as I understand it, the string gets reformatted when you delete a number somewhere, plus the cursor jumps to the end. This makes it hard to do quick and meaningful edits.

I suggest to trap the backspace and delete keys and skip the string reformatting process in that case. This can have side effects but should suit your needs.

function format(input, format, sep) {  var output = "";  var idx = 0;  for (var i = 0; i < format.length && idx < input.length; i++) {    output += input.substr(idx, format[i]);    if (idx + format[i] < input.length) output += sep;    idx += format[i];  }
output += input.substr(idx); return output;}
$('.customerNumberText').keyup(function(e) { if(e.keyCode == 8 //alert('backspace') || e.keyCode == 46) //alert('delete') return;

var foo = $(this).val().replace(/-/g, ""); // remove hyphens // You may want to remove all non-digits here // var foo = $(this).val().replace(/\D/g, "");
if (foo.length > 0) { foo = format(foo, [2, 3, 5, 2, 5], "-"); }
$(this).val(foo);});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="customerNumberText" maxlength="21" />


Related Topics



Leave a reply



Submit