简体   繁体   中英

How to format a string/number to a custom pattern in javascript?

I have a 13 digit value like 1231234123412 and I want to split this number with dots to the following pattern ###.####.####.## .

The resulting value must look like 123.1234.1234.12

How can I split the value in 4 blocks (###.####.####.##) with javascript, angularjs or even a regular expression?

You can start with RegEx. You need to find and replace the contents of the original value and replace it with the value you like.

You might need a script like this:

function addCommas(nStr)
{
    return nStr.substring(0,3) + "." + nStr.substring(3, 7) + "." + nStr.substring(7, 11) + "." + nStr.substring(11, 13);
}

Snippet

 function addCommas(nStr) { return nStr.substring(0,3) + "." + nStr.substring(3, 7) + "." + nStr.substring(7, 11) + "." + nStr.substring(11, 13); } $("#new_number").change(function(){ this.value = addCommas(this.value.replace(',', '')); }); $('#Enter_Number').keyup(function(){ $('#new_number').val($('#Enter_Number').val()).trigger("change"); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> Enter Number: <input type="text" id="Enter_Number" maxlength="13" /><br><br> Format result : <input type="text" id="new_number" >

Preview:

function splitValue(value) {
    return value.substring(0, 3) + "." +     value.substring(3,7)+"."+value.substring(7, 11) + "." + value.substring(11,value.length);
}

alert(splitValue("1231234123412"));

You can use this function.

You can do it like this with substring() :

 var temp = "1231234123412"; temp = temp.substring(0,3) + "." + temp.substring(3, 7) + "." + temp.substring(7, 11) + "." + temp.substring(11, 13); window.alert(temp);

This will only work for a 13 digit number so if that is what you will always have then you should be ok.

The most simple and elegant formatting is using regex:

function fmt3442(str){
  var src = /^(\d{3})(\d{4})(\d{4})(\d{2})$/
  var dst = '$1.$2.$3.$4'
  return str.replace(src, dst)
}

You can use regexp:

var number = "1231234123412";
var temp = (number.substring(0,3) + "." + number.substring(3, 7) + "." + number.substring(7, 11) + "." + number.substring(11, 13)).replace('..', '');
console.log(temp);

Because if number = "1231234" you will get "123.1234", not "123.1234.."

You can do this with plain JavaScript. Define a method and you can format any string you want with any length and pattern you need. The first parameter is the string with the placeholders. 0-12 are the placeholders and must be placed inside { } . The second parameter is a string with the values you want to use.

Look at the method below:

function formatWithPlaceholder(text, values){
  values = values.toString();
  var pattern = /\{\{|\}\}|{(\d+)}/g;
  var formattedString = text.replace(pattern, function(match, group){
      var value;
      if(match === "{{"){
          return "{";
      }
      if(match === "}}"){
         return "}";
      }
      value = values[parseInt(group, 10)];
      return value ? value.toString() : "";
  });
  return (values.length > 0) ? formattedString : "";
}
var resultString = formatWithPlaceholder("{0}{1}{2}.{3}{4}{5}{6}.{7}{8}{9}{10}.{11}{12}","1231234123412");

Here is the fiddle: https://jsfiddle.net/d2f2z937/

Below function use /[a-zA-Z0-9]/ as placeholders, update the regex for your case:

patternFormat('xxx.xxxx.xxxx.xx')('1231234123412')
// => '123.1234.1234.12'

JavaScript Function:

/**
 * Return a currying function with given pattern to format input string
 *
 * For example:
 * ```js
 * patternFormat('xxx.xxxx.xxxx.xx')('1231234123412')
 * // => '123.1234.1234.12'
 * patternFormat('xxx xxx xxxx')('1234567')
 * // => '123 456 7'
 * patternFormat('(xxx) xxx xxxx')('1231231234')
 * // => '(123) 123 1234'
 * patternFormat('YYYY-MM-DD HH:mm:ss')('20220520105430')
 * // => '2022-05-20 10:54:30'
 * patternFormat('$00.00')('1234')
 * // => '$12.34'
 * ```
 *
 * @param {string} pattern
 */
function patternFormat(pattern) {
  // convert pattern into block sections: 'xxx xxxx xxxx' => [3, ' ', 4, ' ', 4]
  const sections = [];
  let i = 0;
  let prevPlaceholder = undefined;
  for (const c of pattern) {
    const placeholder = /[a-zA-Z0-9]/.test(c);
    // init previous placeholder state by first character
    if (prevPlaceholder === undefined) {
      prevPlaceholder = placeholder;
    }

    if (placeholder !== prevPlaceholder) {
      prevPlaceholder = placeholder;
      i++;
    }

    if (placeholder) { // placeholder
      if (i === sections.length)
        sections[i] = 1;
      else
        sections[i]++;
    } else { // separator
      if (i === sections.length)
        sections[i] = c;
      else
        sections[i] += c;
    }
  }

  return function format(str) {
    let result = '';
    let i = 0;
    for (const section of sections) {
      // end if all characters in "str" are consumed
      if (i >= str.length) break;

      if (typeof section === 'number') {
        result += str.substring(i, i + section);
        i += section;
      } else {
        result += section;
      }
    }
    // concat rest characters.
    if (i < str.length) {
      result += str.substring(i);
    }
    return result;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM