Reformatting Strings - Javascript

javascript format string with variables
javascript string format number
string interpolation javascript
jquery string format
typescript string format
javascript format html string
javascript sprintf w3schools
es6 template strings html

I've been given a task that has to reformat incorrect phone numbers (that are strings) in javascript. The correct output has to be: 123-456-789 or 123-456-789-11 (depending on how many characters there are in the string)?

I have a basic java background and am still getting used to the way javascript works...

Example cases:

00-44 48 5555 8361
0 - 22 1985--324
555372654

Example cases should ne:

004-448-555-583-61
022-198-53-24
555-372-654

The code will eventually ignore the dashes and spaces so that correct output can be generated

This is what i have so far:

S = S.replace("", "");

for(var i = 0; i < n; i++) {
    var after = S.replace(/(\d{3})(?=\d)/g, '$1-');
    console.log(after);
} 

Cheers

With S=["00-44 48 5555 8361","0 - 22 1985--324","555372654"]

All you need is one line:

S.map(str=>str.replace(/[- ]/g, "").match(/(\d{1,3})/g).join('-'));

Which will iterate your array of strings, remove all spaces and -, then match 1 to 3 digits (greedy first, so 3 whenever possible) and ultimately join these matches with - between.

Run example below:

console.log(
            ["00-44 48 5555 8361","0 - 22 1985--324","555372654"]
                .map(str=>str.replace(/[- ]/g, '')
                         .match(/(\d{1,3})/g)
                         .join('-')
                    )
           );

Template literals (Template strings), Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. I've been given a task that has to reformat incorrect phone numbers (that are strings) in javascript. The correct output has to be: 123-456-789 or 123-456-789-11 (depending on how many characters t

  1. You used assignment operator(=) instead of equality operator(==) in the if block.

  2. As your code indicate 'n' is the length of the string. So n.replace() will not work.

JavaScript equivalent to printf/String.Format, From ES6 on you could use template strings: let soMany = 10; console.log(`This is ${soMany} times easier!`); // "This is 10 times easier! See Kim's answer below  String methods help you to work with strings. Primitive values, like "John Doe", cannot have properties or methods (because they are not objects). But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.

Some general tips to solve this:

1) You might want to remove whitespaces and dashes from the input first, e.g.:

S = S.replace(" ", "")

2) You can access a certain character in a string by index like this:

S[i] // e.g. "0"

3) To check if you are at the third position were a dash needs to be added, just use modulo on the position:

if(n % 3 === 0) { /* add - */}

4) You can build up a new string and add characters with +=:

let result = "123";
result += "-";

Simple String.format() in javascript (Example), javascript. String.prototype.format = function() { a = this; for (k in arguments) { a = a.replace("{" + k + "}", arguments[k]) } return a }. Usage: reformatting string to two string values in javascript. I have the following code that converts a string that looks like aaa-bbb|ccc-ddd|eee-fff to two strings that look like aaa|ccc|eee and bbb|ddd|fff.

You can use a regular expression to match groups of three digits.

var inputs = ['00-44 48 5555 8361', '0 - 22 1985--324', '555372654', 
              '123456798', '12345678911', '', '1'];

inputs.forEach(function(input) {
    var strippedInput = input.replace(/[\s-]/g, '');
    var formattedInput = strippedInput.replace(/(\d{3})(?=\d)/g, '$1-');
    console.log(formattedInput);
});

JavaScript String Methods, Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java  I made a small improvement so that all instances are replaced rather than just the first. This doesn't change the problem of backward compatibility, but string literals are coming to JS: You might wish to amend your prototyping to match the functionality. One thing to note is that it uses the ` string limiter rather than the single or double

One way to do it, is to first remove all the numbers then split on every third number. Followed by joining the array with a -

const tests = [
  '123-15 68--5722',
  '123-15 68     52',
  '123--125--68--572',
  '123 a b c 15 68 d efg   52',
]

function format(num) {
  // Remove everything that isn't a number
  return num.replace(/[^0-9]/g, '')
    // Spilt on every 3rd number
    .match(/\d{1,3}/g)
    // Join with dashes
    .join('-')
}

tests.forEach(num => console.log(format(num)))

Python String Formatting, Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java  The concat () method is used to join two or more strings. This method does not change the existing strings, but returns a new string containing the text of the joined strings. Browser Support. string .concat ( string1, string2, , stringX) Parameter Values. string1, string2, , stringX. Required. The strings to be joined. Technical Details.

String.Format in JavaScript, Introduction. C# and VB.NET have a nifty Format() function that allows you to pass in a template string (a string that contains placeholders) and  — Javascript and CSS Code beautifier by c7sky, — jsbeautify-for-chrome by Tom Rix , — Pretty Beautiful JavaScript by Will McSweeney — Stackoverflow Code Beautify by Making Odd Edit Studios . Firefox: Javascript deminifier by Ben Murphy, to be used together with the firebug , Safari: Safari extension by Sandro Padin,

JavaScript sprintf, sprintf() for JavaScript is a complete open source JavaScript sprintf implementation. Its prototype is simple: string sprintf(string format , [mixed arg1 [, mixed arg2 [  The ISO format follows a strict standard in JavaScript. The other formats are not so well defined and might be browser specific. Independent of input format, JavaScript will (by default) output dates in full text string format: ISO 8601 is the international standard for the representation of dates and times. The ISO 8601 syntax (YYYY-MM-DD) is

davidchambers/string-format: JavaScript string formatting , Strings in JavaScript have been historically limited, lacking the capabilities one Multiline strings without hacks; String formatting; String tagging for safe HTML  Converting a String to an Array.map() is known to belong to the Array prototype. Let’s use it to convert a String to an Array. We are not developing the method to work for strings here. Rather, we will use the special .call() method. Everything in JavaScript is an object and methods are functions attached to these objects.

Comments
  • If n is the length (an integer), it won't have the .replace method. Did you mean S.replace(…)?
  • Please add the example value(s) for S and the expected output for that particular example.
  • I didn't see that, thanks... But apparently the errors is coming from the if statement: ReferenceError: Invalid left-hand side in assignment)
  • test cases has been added
  • Oh, that as well. You should always include the error message in your question if you are getting one.