当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Javascript:字符串对象(string)的基本操作

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

2017年12月21日  | 移动技术网IT编程  | 我要评论

 

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))
效果图:

 

\

示例代码:

 


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>



 

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网