字符串定义和基本方法介绍

第一部分:

字符串定义: 它是编程语言中的一种基本数据类型,它由数字、字母、下划线组成的一串字符,通常以串联的整体作为操作对象.
  • 定义扩展延伸:

组成的字符可以是 零个 或 多个, 放在 单引号 或者 双引号之间. 如果字符串里面有单引号子内容,则整个字符串就要用 双引号.(如果非要单引号里面使用单引号,那就必须使用 反斜杠 \ 来把引号转义掉)

//双/单引号
var str3 = 'hel'l'o world'
console.log(str3) //  "error"

var str4 = "hel'l'o world"
console.log(str4)  // "hel'l'o world"

// 反斜杠转义
var str5 = "hel'l'o world"
var str6 = 'a\'b\'c'

console.log(str5)  //"hel'l'o world"
console.log(str6)  // "a'b'c"

空格也会占用空间,影响字符串的长度. 如下:

var str1 = 'hello world'
var str2 = 'hello w o rld'
console.log(str1.length) // 11
console.log(str2.length) // 13

字符串格式形式一般都是在同一行内, 如果非要在多行来表示一个字符串,就要用到
①空格+反斜杠 (不推荐)
②使用 + 符号来连接 (推荐)

var str7 = 'hello \
world \
ni \
hao';
console.log(str7) // "hello world ni hao" 


var str8 = 'hello'
+ ' world'
+ ' ni'
+ ' hao';
console.log(str8) // "hello world ni hao"

字符串多行显示方法,使用 `(数字1左边键)小斜点, 这是ES6新增功能

var str9 = `hello 
world
ni 
hao
`
console.log(str9) 
               // 输出结果为:
                          "hello 
                           world
                           ni 
                           hao
                            "

 

第二部分:

为了方便记忆,我们把字符串的基本方法先分类: 查 ,增, 删, 改, 转

  • 长度: string.length
var str1 = 'abc 123'
console.log(str1.length) // 6 注意空格也算一个单位长度
  • 通过索引值来查看所在字符 str[num]
var str = 'hello world '
console.log(str[3]) // "l"

// 注意 这个方法 不能实现 通过赋值来改变 字符串 ,如下:
var str = 'hello world '
str[3] = 'w'
console.log(str) //   "hello world " 原数组不改变, 赋值无效
  • 通过索引值查来找字符: string[num] ; string.charAt(num)
var str = 'hello world'
var str1 = str[2]
var str2 = str.charAt(4)
var str3 = str[20]  // 询查不到返回 undefined 
var str4 = str.charAt(20) // 询查不到返回 "" 

console.log(str1) // "o"
console.log(str2) // "o"
console.log(str3) // undefined 
console.log(str4) // ""
  • 通过字符来查找索引值: string.search('char') ; string.indexOf('char') ; string.lastIndexOf('char')
var str = 'hello world'
var search = str.search('l')
var search1 = str.search('a') // 查询不到 返回 -1
var index = str.indexOf('o')
var index1 = str.indexOf('a')  // 查询不到 返回 -1
var lastIndex = str.lastIndexOf('l')

console.log(search) //2
console.log(search1) //-1
console.log(index)  //4
console.log(index1)  //-1
console.log(lastIndex)  //9
  • string.match('chars') 匹配原数组chars,如果存在,以数组返回chars,不存在 返回 null
var str = 'hello world '
var matchStr = str.match('el')
console.log(matchStr) // ["el"]

var matchStr1 = str.match('le')
console.log(matchStr1) // null

  • 遍历一个字符串,是ES6 新增: for ( .. of ..)
var str = 'hello world'
for (var i of str){
  console.log(i)
}
// "h" "e" "l" "o" " " "w" "o" "r" "l" "d"

// 或者 封装成函数
function ergStr(string){
  for (var i of string){
    console.log(i)
  }
}
ergStr(str) // "h" "e" "l" "o" " " "w" "o" "r" "l" "d"
  • 查看某字符出现的次数 函数 countchar(str,c) :
var str = ' hellw world'
function countchar(str,c){
  count = 0
  for (var char of str){
    if( char == c){
      ++count 
    }
  }
   console.log(count)
}

countchar(str,'l') // 3

  • ''+'' 运算符来 增添字符, 简便,实用 前后都可添加 :
var str = 'hello world'
var strplus = str+'www'
console.log(strplus) // "hello worldwww"

var plusstr = 'ni hao '+str
console.log(plusstr)  // "ni hao hello world"

  • string.concat('chars') 增添字符
var str = 'hello world'
var strconcat = str.concat('yyy')
console.log(strconcat) // ""hello worldyyy""
  • string.replace('char','replacechars') 这个是一个变相的增添,可以在定位的字符后面来添加字符串
var str = 'hello world '
var strPlaceAdd = str.replace('lo','lo this')
console.log(strPlaceAdd) // "hello this world "

删 : 可以删除字符 或 字符段 还是 空格

  • 使用repalce来删除某一个或一段字符, 原字符串不变; 还可以用来删除字符串所有的空格
var str =  'hello world '
var deleteStr = str.replace('e','')
console.log(deleteStr) // " hllo world "

var deleteStr1 = str.replace('ell','')
console.log(deleteStr1) // " ho world "

// 删除所有字符串里所有空格
var deleteSpace = str.replace(/\s*/g,'')
console.log(deleteSpace) // "helloworld"
  • string.trim()删除两边空格,原字符串不变
var str = ' hello world '
var trimStr = str.trim()
console.log(trimStr) // "hello world"

改: 可以引申为 改变,截取,限缩 字符串

  • string.substring(startIndex, endIndex) 截取元素一段字符串, 不改变原数组, 注: 截取不包括endIndex所在字符
var str = 'hello world '
var substring = str.substring(3,8)
console.log(substring)  // "lo wo"  注: 截取不包括endIndex所在字符
  • string.substr(startIndex, length) 从开始索引值截取一段长度的字符串,元字符串不变
var str = 'hello world '
var substr = str.substr(3,8)
console.log(substr)  / "lo world"
  • string.slice(startIndex,endIndex) 截取startIndex 到 endIndex 的字符段, 不包括endIndex所在字符
var str = 'hello world '
var sliceStr = str.slice(3,8)
console.log(sliceStr) // "lo wo"

//注意 slice 允许负数索引值的出现, 表示 倒数的索引值: 
var sliceStr1 = str.slice(3,-2)
console.log(sliceStr1) // "lo worl"
var sliceStr2 = str.slice(-4,-1)
console.log(sliceStr2) // "rld"
  • string.toUpperCase() 和 string.toLowerCase() 全局改变字符成大/小写
var str =  'Hello World '
var upperStr = str.toUpperCase()
var lowerStr = str.toLowerCase()
console.log(upperStr) // "HELLO WORLD "
console.log(lowerStr) // "hello world "

//如果要想改变某个字符的大小写 就用 .replace() 如: 
var reStr = str.replace('lo','LO')
console.log(reStr) // "HelLO World "

字符串与数字,数组,对象的类型转换

  • 转成 数字类型:
    ① parseInt( string ) : 转换为整数, 忽略小数点后面数字 以及 忽略字符串
    ② parseFloat( string) : 转换为浮点型数字,遇到非数字自动舍去,只认识第一个小数点,后面的小数点自动舍去
    ③ Number(string) : 强制转换为数字, 不能有非数字以外类型, 否则返回NaN
var str = '123px'
var floatStr = '123.123px'

// parseInt()
var intNum = parseInt( str )
var intNum1 = parseInt( floatStr )
console.log( intNum )  // 123 
console.log( intNum1 ) // 123

// parseFloat()
var floatNum = parseFloat( floatStr )
console.log( floatNum ) // 123.123

// 注意 parseFloat 只能识别到第一个小数点,如下: 
var floatStr1 = '123.456.789px'
var floatNum1 = parseFloat( floatStr1 )
console.log( floatNum1 ) // 123.456

// Number()
var num = Number(str)
console.log( num ) // NaN

//  数值 转 字符串 
var num = 123456
var numStr1 = num + ''
var numStr2 = num.toString()
console.log(numStr1) // "123456"
console.log(numStr2) // "123456"
  • 转成 数组类型 string.split('separator')
var str = '123,abc,DEF'
var arrStr = str.split(',')
console.log(arrStr) // ["123", "abc", "DEF"]
console.log(str) //  "123,abc,DEF" 不改变原字符串

var arrStr1 = str.split("")
console.log(arrStr1 ) // ["1", "2", "3", ",", "a", "b", "c", ",", "D", "E", "F"]

// 注意 match()方法也是返回一个数组
var matchStr = str.match('3,a')
console.log( matchStr ) // ["3,a"]

// 数组 转换 字符串方法
var arr = ['abc','123','DBC']
var arrStr = arr.join('')
console.log( arrStr ) "abc123DBC"

  • 转成 对象类型 JSON.parse(string)
var str = '{"name": "li", "age": 18, "sex": "male"}'
var objStr = JSON.parse(str)
console.log( objStr ) // { age: 18, name: "li",sex: "male"}

// 对象 转换 字符串方法
var reStr = JSON.stringify( objstr )
console.log( reStr ) // "{"name":"li","age":18,"sex":"male"}"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,539评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,594评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,871评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,963评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,984评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,763评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,468评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,850评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,002评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,144评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,823评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,483评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,026评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,150评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,415评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,092评论 2 355

推荐阅读更多精彩内容