本文实例讲述了Javascript字符串对象(string)基本用法。分享给大家供大家参考,具体如下:
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.jb51.net") + "
")
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 字符串对象 body {background-color:#e6e6e6} (一)length属性:获取字符串的长度 Hello world, Hello javascript!
(二)为字符串添加样式对字符串调用样式的相关方法时,会自动拼接相应的html标签
some words
(三)indexOf方法:定位字符串中某一个指定的字符首次出现的位置 (四)replace()方法:替换字符串中的部分内容
更多关于Javascript相关内容感兴趣的读者可查看本站专题:《Javascript替换操作技巧总结》、《Javascript查找算法技巧总结》、《Javascript数据结构与算法技巧总结》、《Javascript遍历算法与技巧总结》、《Javascript中json操作技巧总结》、《Javascript错误与调试技巧总结》及《Javascript数学运算用法总结》
希望本文所述对大家Javascript程序设计有所帮助。



