本文主要是介绍JavaScript - First step - Strings,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
var string = 'The revolution will not be televised.';
var string = "The revolution will not be televised.";
转义字符
var bigmouth = 'I\'ve got no right to take my place...';
bigmouth;
字符串连接
var one = 'Hello, ';
var two = 'how are you?';
var joined = one + two;
joined;
<button>Press me</button>
var button = document.querySelector('button');button.onclick = function() {var name = prompt('What is your name?');alert('Hello ' + name + ', nice to see you!');
}
Numbers vs. strings
'Front ' + 242;
// 结果是字符串 "Front 242"var myDate = '19' + '67';
typeof myDate;
// "string"
类型转换
var myString = '123';
var myNum = Number(myString);
typeof myNum;
// "number"var myNum = 123;
var myString = myNum.toString();
typeof myString;
// "string"
String 方法
取得字符串长度
var browserType = 'mozilla';
browserType.length;
// 7
取得字符串中的指定字符
browserType[0];
// "m"browserType[browserType.length-1];
// "a"
搜寻字符串中的子串
browserType.indexOf('zilla');
// 2
// 若存在,返回子串的起始索引browserType.indexOf('vanilla');
// -1
// 若不存在,返回 -1
依据起迄索引,取得子串
browserType.slice(0,3);
// "moz"
// 索引0至索引3的字符browserType.slice(2);
// "zilla"
// 索引2至字符串结尾的字符
大小写转换
var radData = 'My NaMe Is MuD';
radData.toLowerCase();
// "my name is mud"var radData = 'My NaMe Is MuD';
radData.toUpperCase();
// "MY NAME IS MUD"
更新字符串中,部分字符
browserType.replace('moz','van');
// "vanilla"
这篇关于JavaScript - First step - Strings的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!