ES6 Basics (3) - Strings

Common String Methods

let str = "js_ytr";
console.log(str.length);//6
console.log(str.charAt(3));//y

console.log(str.substr(1,2));//s_  (起始位置[,字符数])
console.log(str.substring(1,2));//s  (起始位置[,结束位置])
console.log(str.slice(1,2));//s (beginSlice[, endSlice])

console.log(str.indexOf("_", 1));//2 (要查询的字符串[,查询起始位置])
console.log(str.indexOf("_", 3));//-1 取str第一次出现的索引 找不到时返回-1
console.log(str.lastIndexOf("_",5));//2  (要查询的字符串[,查询起始位置]) 取str最后一次出现的索引 从右往左 找不到时返回-1

console.log(str.toUpperCase());//JS_YTR
console.log(str.toLowerCase());

console.log(" str".trim());//str 删除字符串两端的空白字符
console.log(str.concat("88", "66"));//js_ytr8866  将多个字符串与原字符串合并为一个新字符串
console.log(str.link("https://www.baidu.com/"));//<a href="https://www.baidu.com/">js_ytr</a>link() 方法创建一个 <a> HTML 元素,用该字符串作为超链接的显示文本,参数作为指向另一个 URL 的超链接。
console.log(str.repeat(2));//js_ytrjs_ytr  表示将原字符串重复n次。 'na'.repeat(0) // "" 'na'.repeat(NaN) // ""

//正则相关
console.log(str.replace("js", "java"));//java_ytr str.replace(regexp|substr, newSubStr|function)
console.log(str.split("_"));//[ 'js', 'ytr' ] ([separator[, limit]]) separator 可以是一个字符串或正则表达式  limit限定返回的分割片段数量
console.log(str.split("_", 1));//[ 'js' ]
console.log(str.split("_", 0));//[]
console.log(str.search("_"));//2  (regexp) 返回正则表达式在字符串中首次匹配项的索引。否则,返回 -1。
console.log(str.match("_"));//[ '_', index: 2, input: 'js_ytr' ]  str.match(regexp)如果字符串匹配到了表达式,会返回一个数组,数组的第一项是进行匹配完整的字符串,之后的项是用圆括号捕获的结果。如果没有匹配到,返回null

Traditionally, JavaScript has only had the indexOf method, which can be used to determine whether a string is contained within another string. ES6 provides three new methods.

  • includes(): Returns a boolean value indicating whether the parameter string was found.
  • startsWith(): Returns a boolean value indicating whether the parameter string is at the head of the original string.
  • endsWith(): Returns a boolean value indicating whether the parameter string is at the end of the original string.
let s = 'Hello world!';

s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true
//这三个方法都支持第二个参数,表示开始搜索的位置。
s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false

ES2017 introduced the ability to complete the length of strings. If a string is not long enough, it will be filled at the head or tail. padStart() is used for head completion and padEnd() is used for tail completion.

//第一个参数用来指定字符串的长度,第二个参数是用来补全的字符串。
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'

'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'

'xxx'.padStart(2, 'ab') // 'xxx'
'xxx'.padEnd(2, 'ab') // 'xxx'
'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
'09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"

Template strings are enhanced strings, denoted by backticks (`). It can be used as a normal string, it can also be used to define multi-line strings, or to embed variables in strings.

// 普通字符串
`In JavaScript '\n' is a line-feed.`

// 多行字符串
`In JavaScript this is
 not legal.`

console.log(`string text line 1
string text line 2`);

// 字符串中嵌入变量
let name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

//模板字符串之中还能调用函数。
function fn() {
  return "Hello World";
}

`foo ${fn()} bar`

Template strings do more than just the above. It can immediately follow the name of a function that will be called to process this template string. This is called the "tagged template" feature. One of its important applications is to filter HTML strings to prevent users from entering malicious content, see Tag Templates for details

let message =
  SaferHTML`<p>${sender} has sent you a message.</p>`;

function SaferHTML(templateData) {
  let s = templateData[0];
  for (let i = 1; i < arguments.length; i++) {
    let arg = String(arguments[i]);

    // Escape special characters in the substitution.
    s += arg.replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;");

    // Don't escape special characters in the template.
    s += templateData[i];
  }
  return s;
}

Something about string applications

//实现字符串的逆序输出
let str = "js_yt2r";
console.log(str.split('').reverse().join(''));//r2ty_sj

//删除字符串中所有的数字
let s = "rty_s2j";
console.log(s.replace(/\d/g,''));//rty_sj

//遍历字符串 采用for of
for (let c of "str") {
  console.log(c);//s t r
}

See
MDN web docs - JavaScript reference documentation
Getting started with ECMAScript 6

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325501597&siteId=291194637