Jimliu


一只刚上路的前端程序猿


string字符串方法

来自《javascript高级程序设计》的学习笔记

1.访问字符串中特定字符的方法 charAt()和charCodeAt()

var string = "hello javascript"
console.log(string.charAt(1))  //'e'
console.log(string.charCodeAt(1)) //'101'

charCodeAt方法返回的是字母”e”的字符编码,与前两种方法有一种类似的方法是stringValue[1]访问第一个字符。

2.字符串连接方法concat(),concat()方法可接受多个参数

var string = "hello"
var result = string.concat("world");
console.log(result)  // hello world

3.三个基于子字符串创建新字符串的方法 slice(),substr(),substring()

这三个方法都会返回被操作字符串的子字符串,而且都接受一到两个参数

3.1:当他们都接受一个参数的时候返回值是一样的。
var string = "hello,world";
console.log(string.slice(3));   // "lo,world"
console.log(string.substr(3));  // "lo,world"
console.log(string.substring(3)); // "lo,world"
3.2:当他们接受两个参数时,情况就不太一样了slice和substring的两个参数是”开始位置”,”结束位置”而substr的两个参数是”开始位置”,”截取长度”。
var string = "hello,world";
console.log(string.slice(3,7));   // "lo,w"
console.log(string.substr(3,7));  // "lo,w"
console.log(string.substring(3,7)); // "lo,worl"

因为参数为负的情况现阶段用不到,所以暂且不考虑。

4.trim()方法:去除字符串前缀及后置的空格,刚好在百度ife的任务中看到了这个题,第一步很简单,就直接使用trim方法。

var string = "    hello,world   ";
var newString = string.trim();
console.log(newString)   //"hello,world"

字符串方法暂时先介绍到这里,欢迎大家指正。

最近的文章

学习计划

五月最后一周学习计划 学习baidu-ife task0003中的”JavaScript深度学习” JavaScript作用域学习笔记JavaScript原型学习笔记JavaScript闭包学习笔记JavaScript构造函数学习笔记JavaScript面向对象编程学习笔记JavaScript设计模 …

于  前端, 学习, 计划 继续阅读
更早的文章

javascript学习笔记1————作用域

javascript学习笔记1————执行环境及作用域在javascript中每一段代码都有执行环境,全局变量和函数都是作为window对象那个的属性和方法创建的。某个执行环境中的所有代码被执行完毕后,该环境就会被销毁,包括其中的变量及函数定义。 …

于  javascript, 前端 继续阅读