JavaScript 字串方法(二)

來源:互聯網
上載者:User

標籤:比較   ase   split   括弧   asc   search方法   Regex   位置   javascrip   

字串大小寫轉換方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>大小寫轉換</title>
</head>
<body>
<script type="text/javascript">
var str="HELLO world";
console.log(str.toLowerCase());//hello world
console.log(str.toUpperCase());//HELLO WORLD
</script>
</body>
</html>
字串模式比對方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>字串模式比對</title>
</head>
<body>
<script type="text/javascript">
/*
match方法:只接受一個參數,由字串或RegExp對象指定的一個Regex
search方法:只接受一個參數,由字串或RegExp對象指定的一個Regex
search方法返回字串中第一個匹配項的索引,如果沒有匹配項,返回-1
*/
var str="cat,bat,sat,fat";
var pattern=/.at/;
var matches=str.match(pattern);
console.log(matches.index);//0
console.log(matches[0]);//cat
console.log(pattern.lastIndex);//0
//lastIndex表示開始搜尋下一個匹配項的字元位置,從0算起
var pos=str.search(/at/);
console.log(pos);//1 1表示at字串在原來字串中第一次出現的位置
</script>
</body>
</html>
replace方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>replace方法</title>
</head>
<body>
<script type="text/javascript">
var str="cat,bat,sat,fat";
var res=str.replace("at","one");//第一個參數是字串,所以只會替換第一個子字串
console.log(res);//cone,bat,sat,fat

var res1=str.replace(/at/g,"one");//第一個參數是Regex,所以會替換所有的子字串
console.log(res1);//cone,bone,sone,fone
</script>
</body>
</html>
split方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>split方法</title>
</head>
<body>
<script type="text/javascript">
/*
split方法是基於指定的字元,將字串分割成字串數組
當指定的字元為空白字串時,將會分隔整個字串
*/
var str="red,blue,green,yellow";
console.log(str.split(","));//["red", "blue", "green", "yellow"]
console.log(str.split(",",2));//["red", "blue"] 第二個參數用來限制數組大小
console.log(str.split(/[^\,]+/));// ["", ",", ",", ",", ""]
//第一項和最後一項為空白字串是因為Regex指定的分隔字元出現在了子字串的開頭,即"red"和"yellow"
//[^...] 不在方括弧內的任一字元 只要不是逗號都是分隔字元
</script>
</body>
</html>
localeCompare方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>localeCompare方法</title>
</head>
<body>
<script type="text/javascript">
/*
這個方法用於比較兩個字串
1.如果字串在字母表中應該排在字串參數之前,則返回一個負數
1.如果字串等於字串參數,則返回0
1.如果字串在字母表中應該排在字串參數之後,則返回一個正數
*/
var str="yellow";
console.log(str.localeCompare("brick"));//1
console.log(str.localeCompare("yellow"));//0
console.log(str.localeCompare("zoo"));//-1
</script>
</body>
</html>

JavaScript 字串方法(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.