Web开发技术梳理 0x8 JavaScript(0x5)文本格式化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/funkstill/article/details/88861129

字符串

    JavaScript中的 String 类型用于表示文本型的数据. 它是由无符号整数值(16bit)作为元素而组成的集合. 字符串中的每个元素在字符串中占据一个位置. 第一个元素的index值是0, 下一个元素的index值是1, 以此类推. 字符串的长度就是字符串中所含的元素个数.

     String字面量

  • 16进制转义序列
'\xA9' // "©"
  • Unicode转义序列
'\u00A9' // "©"
  • Unicode字元逸出

    ECMAScript 6中的新特性。有了Unicode字元逸出,任何字符都可以用16进制数转义, 这使得通过Unicode转义表示大于0x10FFFF的字符成为可能。使用简单的Unicode转义时通常需要分别写字符相应的两个部分(大于0x10FFFF的字符需要拆分为相应的两个小于0x10FFFF的部分)来达到同样的效果。

'\u{2F804}'

// the same with simple Unicode escapes
'\uD87E\uDC04'

     字符串对象

    String 对象是对原始string类型的封装 .

var s = new String("foo"); // Creates a String object
console.log(s); // Displays: { '0': 'f', '1': 'o', '2': 'o'}
typeof s; // Returns 'object'

    除非必要, 应该尽量使用String字面值, 因为String对象的某些行为可能并不与直觉一致. 

var s1 = "2 + 2"; // Creates a string literal value
var s2 = new String("2 + 2"); // Creates a String object
eval(s1); // Returns the number 4
eval(s2); // Returns the string "2 + 2"

    String对象的方法

     多行模板字符串

    模板字符串是一种允许内嵌表达式的String字面值. 可以用它实现多行字符串或者字符串内插等特性.

  • 多行
console.log(`string text line 1
string text line 2`);
// "string text line 1
// string text line 2"
  • 嵌入表达式
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20."

国际化

    Intl 对象是ECMAScript国际化API的命名空间, 提供了语言敏感的字符串比较,数字格式化和日期时间格式化功能.  Collator, NumberFormat, 和 DateTimeFormat 对象的构造函数是Intl对象的属性.

    时间和日期国际化

/*把一个日期格式化为美式英语格式.*/
var msPerDay = 24 * 60 * 60 * 1000;
 
// July 17, 2014 00:00:00 UTC.
var july172014 = new Date(msPerDay * (44 * 365 + 11 + 197));//2014-1970=44年
//11是闰年中多出的天数。。。
//197是6×30+16(7月的16天)+3(3个大月)-2(2月少2天)

var options = { year: "2-digit", month: "2-digit", day: "2-digit",
                hour: "2-digit", minute: "2-digit", timeZoneName: "short" };
var americanDateTime = new Intl.DateTimeFormat("en-US", options).format;
 
console.log(americanDateTime(july172014)); // 07/16/14, 5:00 PM PDT

     数字格式化

var gasPrice = new Intl.NumberFormat("en-US",
                        { style: "currency", currency: "USD",
                          minimumFractionDigits: 3 });
 
console.log(gasPrice.format(5.259)); // $5.259

var hanDecimalRMBInChina = new Intl.NumberFormat("zh-CN-u-nu-hanidec",
                        { style: "currency", currency: "CNY" });
 
console.log(hanDecimalRMBInChina.format(1314.25)); // ¥ 一,三一四.二五

    定序

    Collator 对象在字符串比较和排序方面很有用.

/*德语中有两种不同的排序方式 电话本(phonebook)
 和 字典(dictionary). 电话本排序强调发音, 比如
 在排序前 “ä”, “ö”等被扩展为 “ae”, “oe”等发音.*/
var names = ["Hochberg", "Hönigswald", "Holzman"];
 
var germanPhonebook = new Intl.Collator("de-DE-u-co-phonebk");
 
// as if sorting ["Hochberg", "Hoenigswald", "Holzman"]:
console.log(names.sort(germanPhonebook.compare).join(", "));
// logs "Hochberg, Hönigswald, Holzman"

猜你喜欢

转载自blog.csdn.net/funkstill/article/details/88861129