欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Javascript:字符串对象(string)的基本操作

程序员文章站 2022-04-14 11:49:20
  1.获取字符串的长度:   var s = Hello world; document.write(length:+s.length); 2.为字符串添加...

 

1.获取字符串的长度:

 

var s = Hello world;
document.write(length:+s.length);
2.为字符串添加各种样式,如:

 

 

var txt = Some words;
document.write(

Big: + txt.big() +

) document.write(

Small: + txt.small() +

) document.write(

Bold: + txt.bold() +

) document.write(

Italic: + txt.italics() +

) document.write(

Blink: + txt.blink() + (does not work in IE)

) document.write(

Fixed: + txt.fixed() +

) document.write(

Strike: + txt.strike() +

) document.write(

Fontcolor: + txt.fontcolor(Red) +

) document.write(

Fontsize: + txt.fontsize(16) +

) document.write(

Link: + txt.link(https://www.w3school.com.cn) +

)3.获取字符串中部分内容首次出现的位置:

 

 

var hw_text = Hello world;
document.write(hw_text.indexOf(Hello)+
);
document.write(hw_text.indexOf(world)+
);
document.write(hw_text.indexOf(abc)+
);
4.内容替换:

 

 

var str=Visit Microsoft!
document.write(str.replace(/Microsoft/,W3School))
效果图:

 

Javascript:字符串对象(string)的基本操作

示例代码:

 


body {background-color:#e6e6e6} (一)length属性:获取字符串的长度

Hello world, Hello javascript!

<script> var s = document.getElementById(hw).innerHTML; document.write(length:+s.length); </script> (二)为字符串添加样式

对字符串调用样式的相关方法时,会自动拼接相应的html标签

some words

Call txt.big()<script> var txt = document.getElementById(hw_02).innerHTML; document.write(

Big: + txt.big() +

) document.write(

Small: + txt.small() +

) document.write(

Bold: + txt.bold() +

) document.write(

Italic: + txt.italics() +

) document.write(

Blink: + txt.blink() + (does not work in IE)

) document.write(

Fixed: + txt.fixed() +

) document.write(

Strike: + txt.strike() +

) document.write(

Fontcolor: + txt.fontcolor(Red) +

) document.write(

Fontsize: + txt.fontsize(16) +

) document.write(

Link: + txt.link(https://www.w3school.com.cn) +

) function alertBig(){ alert(txt.big()); } </script> (三)indexOf方法:定位字符串中某一个指定的字符首次出现的位置 <script> var hw_text = Hello world; document.write(hw_text.indexOf(Hello)+
); document.write(hw_text.indexOf(world)+
); document.write(hw_text.indexOf(abc)+
); </script> (四)replace()方法:替换字符串中的部分内容 <script> var str=Visit Microsoft! document.write(str.replace(/Microsoft/,W3School)) </script>