JavaScript實例1

JavaScript不只是簡單的構建塊

JavaScript對象、基本類型和字面值之間的區別

對象:Object windwow 數組、正則、日期、原型、使用 new 通過構造方法創建的
基本類型:字符串、數值、布爾類型、null和undefined,只有字符串、數組和布爾值有構造函數,其餘兩種都是字面值
字面值

var str1 = "this is a  simple string";
var num1 = 1.45;
var answer = true;

當你使用嚴格相等性來比較一個對象示例和一個字面值的時候,可以快速區分出一個基本類型和一個對象實例:即基本類型變量嚴格地等於字面值

var str1 = String("string");
var num1 = Number(1.45);
var bool1 = Boolean(true);

if(str1 ==="string") 
  console.log('equal');
if(num1 === 1.45)
  console.log('equal');
if(bool1 === true)
  console.log('equal');

var str2 = new String("string");
var num2 = new Number(1.45);
var bool2 = new Boolean(true);

if(str2 ==="string") 
  console.log('equal');
else  console.log('not equal');
if(num2 === 1.45)
  console.log('equal');
else  console.log('not equal');
if(bool2 === true)
  console.log('equal');
else  console.log('not equal');
輸出:
"equal"
"equal"
"equal"
"not equal"
"not equal"
"not equal"

從字符串提取出一個列表

1 使用 trim去掉多餘的空格
2 使用正則表達式去掉多餘的空格

var sentence = 'This is one sentence.This is a sentence with a list of items:'+
    'cherries , oranges , apples,bananas.That was the list of lists.';
var start = sentence.indexOf(':');
var end = sentence.indexOf('.',start+1);
var listStr = sentence.substring(start+1,end);

var fruits = listStr.split(',');
fruits.forEach(function(elem,index,array){
  array[index] = elem.trim();
});
var fruits2 = listStr.split(/\s*,\s*/);
console.log(fruits);
console.log(fruits2);

檢查一個存在的、非空的字符串

//var unknownVairable = new String("string");
var unknownVairable = "string";
if(((typeof unknownVairable != 'undefined' && unknownVairable) && unknownVairable.length > 0) && typeof unknownVairable.valueOf()=='string'){
  console.log(true);
}

插入特殊的字符

解決方案:使用轉義序列,例如要想添加到頁面的一段文本中添加一個版權符號
轉義序列最重要的用法之一,是在雙引號或單引號分隔開的字符串中,包含雙引號或單引號:

var newString = 'you can\'t use single quotes '+
    'in a string surrounded by single quotes.'+
    'Oh,wait a sec... yes you can.';
console.log(newString);
輸出:
"you can't use single quotes in a string surrounded by single quotes.Oh,wait a sec... yes you can."

找到並突出顯示一個模式的所有實例

var searchString = "Now is the time and this is the time and that is the time";
var pattern = /t\w*e/g;
var matchArray;
var str = "";
while((matchArray = pattern.exec(searchString))!=null){
  str+= "at  "+ matchArray.index+" we found "+ matchArray[0] +"\n";

}
console.log(str);
輸出:
"ime";
var pattern = /t\w*e/g;
var matchArray;
var str = "";
while((matchArray = pattern.exec(searchString))!=null){
  str+= "at  "+ matchArray.index+" we found "+ matchArray[0] +"\n";

}
console.log(str);
var re = /a(p+).*(pie)/ig;//全局標誌,觸發了RegExp對象去保留每一次匹配的位置,並且從之前找到的匹配之後開始搜索。
var result = re.exec("The apples in the apple pie are tart");
console.log(result);
console.log(result.index);
console.log(result.input);
Console Run  Clear
"at  7 we found the
at  11 we found time
at  28 we found the
at  32 we found time
at  49 we found the
at  53 we found time
"

var re = /a(p+).*(pie)/ig;
var result = re.exec("The apples in the apple pie are tart");
console.log(result);
console.log(result.index);
console.log(result.input);
輸出:
["apples in the apple pie", "pp", "pie"]
4
"The apples in the apple pie are tart"

使用exec和全局標誌來查找並突出顯示一個文字字符串中的所有匹配

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Searching for strings</title>
  <style type="text/css">
    .found{
        background-color: #ff0;
    }
  </style>
</head>
<body>
  <form id="textsearch">
    <textarea name="" id="incoming" cols="150" rows="10"></textarea>
    <p>Search pattern:<input type="text" id="pattern" name=""></p>
  </form>
  <button id="searchSubmit">Search for pattern</button>
<div id="searchResult"></div>

  <script type="text/javascript">
  window.onload= function(){
    document.getElementById("searchSubmit").onclick = function(){
        //獲取模式
        var pattern = document.getElementById("pattern").value;
        var re = new RegExp(pattern, "g");

        //獲取字符串
        var searchString = document.getElementById("incoming").value;

        var matchArray;
        var resultString ="<pre>";
        var first = 0;
        var last = 0;

        while((matchArray = re.exec(searchString))!=null){
            last = matchArray.index;
            //獲取所有匹配的字符串,將其連接起來
            resultString += searchString.substring(first, last);

            //使用class,添加匹配的字符串
            resultString +="<span class='found'>"+matchArray[0]+"</span>";
            first = re.lastIndex;
        }

        //完成字符串
        resultString += searchString.substring(first,searchString.length);
        resultString +="</pre>";

        //插入到頁面
        document.getElementById("searchResult").innerHTML = resultString;
    }
  };

  </script>
</body>
</html>


這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章