server.txt內容如下:
阿里雲服務器
關於應用場景,就不多說了,字符串是不論是后端開發還是前端開發等,都是要經常打交道了。
test.js(node.js代碼,只要被本地裝了node.js環境,直接可通過node test.js運行看效果):
var fs = require("fs"); var result = fs.readFileSync("./server.txt"); console.log("result:"+result); if(result.indexOf("阿里雲服務器") != -1){ console.log("ok"); } else{ console.log("no"); } //indexOf() 方法可返回某個指定的字符串值在字符串中首次出現的位置。如果要檢索的字符串值沒有出現,則該方法返回 -1。 if(result.toString().search("1") != -1){ console.log("ok"); }else{ console.log("no"); } //search() 方法用於檢索字符串中指定的子字符串,或檢索與正則表達式相匹配的子字符串。如果沒有找到任何匹配的子串,則返回 -1。 var reg = RegExp(/阿里雲/); if(result.toString().match(reg)){ console.log("ok"); }else{ console.log("no"); } //match() 方法可在字符串內檢索指定的值,或找到一個或多個正則表達式的匹配。 var reg = RegExp(/阿里雲/); if(reg.test(result)){ console.log("ok"); }else{ console.log("no"); } //test() 方法用於檢索字符串中指定的值。返回 true 或 false。 var reg = RegExp(/阿里雲/); if(reg.exec(result)){ console.log("ok"); }else{ console.log("no"); } //exec() 方法用於檢索字符串中的正則表達式的匹配。返回一個數組,其中存放匹配的結果。如果未找到匹配,則返回值為 null。
本文主要參考資料如下:
js 判斷字符串中是否包含某個字符串