標籤:rip 測試 位置 case hello 調用 script 串連 rom
js操作字串
from:https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001434499203693072018f8878842a9b0011e3ff4e38b6b000
模板字串
要把多個字串串連起來,可以用+號串連:
var name = ‘小明‘;
var age = 20;
var message = ‘你好, ‘ + name + ‘, 你今年‘ + age + ‘歲了!‘;
alert(message);
如果有很多變數需要串連,用+號就比較麻煩。ES6新增了一種模板字串,表示方法和上面的多行字串一樣,但是它會自動替換字串中的變數:
var name = ‘小明‘;
var age = 20;
alert(`你好, ${name}, 你今年${age}歲了!`);
var name = ‘小明‘;
var age = 20;
var message = `你好, ${name}, 你今年${age}歲了!`;
alert(message);
練習:測試你的瀏覽器是否支援ES6模板字串,如果不支援,請把模板字串改為+串連的一般字元串:
// 如果瀏覽器支援模板字串,將會替換字串內部的變數:
var s = ‘Hello, world!‘;
s.length; // 13
var s = ‘Hello, world!‘;
s[0]; // ‘H‘
s[6]; // ‘ ‘
s[7]; // ‘w‘
s[12]; // ‘!‘
s[13]; // undefined 超出範圍的索引不會報錯,但一律返回undefined
JavaScript為字串提供了一些常用方法,注意,調用這些方法本身不會改變原有字串的內容,而是返回一個新字串:
toUpperCase
toUpperCase()把一個字串全部變為大寫:
var s = ‘Hello‘;
s.toUpperCase(); // 返回‘HELLO‘
toLowerCase
toLowerCase()把一個字串全部變為小寫:
var s = ‘Hello‘;
var lower = s.toLowerCase(); // 返回‘hello‘並賦值給變數lower
lower; // ‘hello‘
indexOf
indexOf()會搜尋指定字串出現的位置:
var s = ‘hello, world‘;
s.indexOf(‘world‘); // 返回7
s.indexOf(‘World‘); // 沒有找到指定的子串,返回-1
substring
substring()返回指定索引區間的子串:
var s = ‘hello, world‘
s.substring(0, 5); // 從索引0開始到5(不包括5),返回‘hello‘
s.substring(7); // 從索引7開始到結束,返回‘world‘
js操作字串