Heim  >  Artikel  >  Web-Frontend  >  JavaScript中string对象_javascript技巧

JavaScript中string对象_javascript技巧

WBOY
WBOYOriginal
2016-05-16 15:55:211215Durchsuche

一.String:存储一个字符串,并且提供处理字符串需要的属性和方法。

1.创建String对象:显示和隐式

<DOCTYPE html>
<html>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
  <head>
    <title>js函数</title>
  </head>
  <script type="text/javascript">
     //申明String对象的两种方式:显式和隐式申明
     //1.隐式
     var myString="abc";
     document.write(myString+"<br/>");
     //2.显式
     var myString2=new String("abc");
     document.write(myString2+"<br/>");
  </script>
  <body>
  
  </body>
</html>

*显式和隐式申明String对象,类型不一样:隐式申明的string对象,类型是string,而显式申明的string对象,类型是object。

*显式与隐式创建字符串真正的区别是,如果你要重复使用同样的字符串,显式地创建字符串,有更高的效率;

*显式地创建字符串,还有利于JavaScript解释器混淆数字和字符串;

2.使用String对象的方法

String对象,有许多方法,这里只讨论两个。indexOf()和substring()方法;注意大小写。

*需要知道的:JavaScript字符串,是由字符组成的。这些字符的每一个都有一个索引。这个索引是从0开始的,所以第一个位置的索引是0;第二个是1,以此类推。

*方法indexOf()查找并返回子字符串起始的索引位置,如果查找的元素不存在,就返回-1,否则返回这个字符所在的索引。(lastIndexOf则返回子字符串结束的位置)

下面写一个判断用户数输入的Email地址中,是否包含@符号的例子:

<DOCTYPE html>
<html>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
  <head>
    <title>js函数</title>
  </head>
  <script type="text/javascript">
     //让用户输入Email地址,检查输入是否包含@符号
     //使用prompt方法,获取用户输入的Email地址,检查是否包含@符号,使用indexof返回@符号的索引
     var userInput=prompt("Please enter your email address","Email");
     if(Number(userInput.indexOf("@"))==-1)
     {
      document.write("对不起,您输入的Email不合法");
     }
     else
     {
     document.write("恭喜您,您输入的Email通过验证");
     }
  </script>
  <body>
  </body>
</html>

substring()方法,使用字符串的起始位置和结束位置的索引作为参数,从另一个字符串中截取一个字符串。可以不使用第二个参数,来返回,从第一个索引到字符串结束的所有字符串。比如,我们要截取从第三个到第六个字符的所有字符,可以这样写:

<DOCTYPE html>
<html>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
  <head>
    <title>js函数</title>
  </head>
  <script type="text/javascript">
    //从起始位置,到结束位置
    var myhello="Hello Javascript World";
    var newMyhello= myhello.substring(0);
    document.write(newMyhello+"<br/>");
    //从第三个字符到第六个字符
     var myhello="Hello Javascript World";
    var newMyhello= myhello.substring(2,5);
    document.write(newMyhello+"<br/>");
  </script>
  <body>
  </body>
</html>

以上所述就是本文的全部内容了,希望大家能够喜欢。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn