The wijmo.format Method

Creating strings based on formatted data can be challenging in JavaScript. ES2016 addressed that limitation by introducing Template Strings.

Unfortunately, browser support is still limited for that solution. Hence, we provide the format function that works regardless of browser. The format function takes a format string with placeholders that contain variable names and format specifiers, and a data object that supplies the variables.

For example:

wijmo.format('Welcome {name}! You have {miles:n0} miles in your account.', {
  name: 'Joe',
  miles: 2332123
})


Another example:

wijmo.format('{name}, thanks for being a customer since {date:D}.', {
  name: 'Joe',
  date: new Date()
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// This file locates: "Scripts/Lesson/C1Mvc/WijmoFormat.js".
c1.documentReady(function () {
    // first example
    document.getElementById('btnFormat1').addEventListener('click', function () {
        var msg = wijmo.format('Welcome {name}! You have {miles:n0} miles in your account.', {
            name: 'Joe',
            miles: 2332123
        });
        alert(msg);
    });
 
    // second example
    document.getElementById('btnFormat2').addEventListener('click', function () {
        var msg = wijmo.format('{name}, thanks for being a customer since {date:D}.', {
            name: 'Joe',
            date: new Date()
        });
        alert(msg);
    });
});
1
2
3
4
5
6
7
8
9
10
11
12
13
using System.Web.Mvc;
 
namespace LearnMvcClient.Controllers
{
    public partial class C1MvcController : Controller
    {
        // GET: WijmoFormat
        public ActionResult WijmoFormat()
        {
            return View();
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<h1>
    @Html.Raw(Resources.C1Mvc.WijmoFormat_Title)
</h1>
<p>
    @Html.Raw(Resources.C1Mvc.WijmoFormat_Text1)
</p>
<p>
    @Html.Raw(Resources.C1Mvc.WijmoFormat_Text2)
</p>
 
<p>
    @Html.Raw(Resources.C1Mvc.WijmoFormat_Text3)
</p>
<pre>wijmo.format('Welcome {name}! You have {miles:n0} miles in your account.', {
  name: 'Joe',
  miles: 2332123
})</pre>
<button id="btnFormat1" class="btn btn-default">
    @Html.Raw(Resources.C1Mvc.WijmoFormat_Text4)
</button>
 
<br><br>
<p>
    @Html.Raw(Resources.C1Mvc.WijmoFormat_Text5)
</p>
<pre>wijmo.format('{name}, thanks for being a customer since {date:D}.', {
  name: 'Joe',
  date: new Date()
})</pre>
<button id="btnFormat2" class="btn btn-default">
    @Html.Raw(Resources.C1Mvc.WijmoFormat_Text4)
</button>