javascript實現英文首字母大寫總結

來源:互聯網
上載者:User

javascript實現英文首字母大寫總結

   javascript實現英文首字母大寫總結

        本文給大家總結了幾種可以實現英文首字母大寫的javascript指令碼,另附上一個CSS的實現方法,非常的簡單實用,這裡推薦給大家,有需要的小夥伴可以參考下。

  方法一:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

function replaceStr(str){ // 正則法

str = str.toLowerCase();

var reg = /\b(\w)|\s(\w)/g; // \b判斷邊界\s判斷空格

return str.replace(reg,function(m){

return m.toUpperCase()

});

}

 

function replaceStr1(str){

str = str.toLowerCase();

var strTemp = ""; //新字串

for(var i=0;i<str.length;i++){

if(i == 0){

strTemp += str[i].toUpperCase(); //第一個

continue;

}

if(str[i] == " " && i< str.length-1){ //空格後

strTemp += " ";

strTemp += str[i+1].toUpperCase();

i++;

continue;

}

strTemp += str[i];

}

return strTemp;

}

 

 

var text = "abcd ABCD efGH";

console.log(replaceStr(text));//Abcd Abcd Efgh

console.log(replaceStr1(text));//Abcd Abcd Efgh

  方法二:

  ?

1

2

3

4

5

6

7

8

9

10

11

<script type="text\javascript">

function ucfirst(str){

var str = str.toLowerCase();

var strarr = str.split(' ');

var result = '';

for(var i in strarr){

result += strarr[i].substring(0,1).toUpperCase()+strarr[i].substring(1)+' ';

}

return result;

}

</script>

  方法三:

  ?

1

2

3

4

5

6

7

8

<script type="text\javascript">

function ucfirst(str) {

var str = str.toLowerCase();

str = str.replace(/\b\w+\b/g, function(word){

return word.substring(0,1).toUpperCase()+word.substring(1);

});

return str;

</script>

  CSS來實現:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<html>

<head>

<style type="text/css">

h1 {text-transform: uppercase}

p.uppercase {text-transform: uppercase}

p.lowercase {text-transform: lowercase}

p.capitalize {text-transform: capitalize }

</style>

</head>

<body>

<h1>This Is An H1 Element</h1>

<p class="uppercase">This is a test.</p><p class="lowercase">This is a test.</p><p class="capitalize">This is a test.</p>

</body>

</html>

  以上就是給大家總結的4種實現英文首字母大寫的方法,希望大家能夠喜歡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.