企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
1.1 连接两个或多个字符串 ``` var string1 = "this is a "; var string2 = "test"; var string2 = string1 + string2; ``` 1.2 连接字符串和另一种数据类型 ``` var numValue = 23.45; var total = "and the total is" + numValue; ``` 1.3 条件比较字符串 ``` var strName = prompt("what's your name?",""); if(strName == "shelley"){ alert("your name is shelley!good for you"); }else{ alert("your name isn't shelley.bummer"); } //运算符 说明示例 //相等 == //严格相等 === //不相等 != //严格不相等 !== //大于 > //大于或等于 >= //小于 < //小于或等于 <= ``` 1.4 在字符串中查找子字符串 ``` var testValue = "this is the cookbook's test string"; var subsValue = "cookbook"; var iValue = testValue.indexOf(subsValue); ``` 返回一个数字,表示子字符串的第一个字符的索引或者位置,0表示字符串的第一个字符的索引位置。如果返回-1,那么表示没有找到子字符串 1.5 从一个字符串提取子字符串 ``` var sentence = "this is one sentence.this is a sentence with a list of items:cherries,oranges,apples,bananas."; var start = sentence.indexOf(":"); var end = sentence.indexOf(".",start); var list = sentence.substring(start+1,end); ``` 1.6 检查一个存在的、非空的字符串 ``` if(((typeof unknownVariable != "undefined") && (typeof unknownVariable.valueOf() == "string")) && (unknownVariable.length > 0)){ alert("is true"); } ``` 1.7 将一个关键字字符串分解为单独的关键字 ``` <script> window.onload = function(){ var keywordList = prompt("Enter keywords,separated by commas",""); var arrayList = keywordList.split(","); var resultString = ""; for(var i = 0;i < arrayList.length;i++){ resultString += "keyword:" + arrayList[i] + "<br />"; } var blk = document.getElementById("result"); blk.innerHTML = resultString; } </script> <div id="result"></div> ``` 1.8 插入特殊字符 ``` <div id="result"></div> <script> var resultString = "this page shelley powers"; var blk = document.getElementById("result"); blk.innerHTML = resultString; // 序列 字符 // \' 单引号 // \" 双引号 // \\ 反斜杠 // \b 退格 // \f 换页符 // \n 换行 // \r 回车 // \t 水平制表符 // \ddd 八进制序列 // \xdd 十六进制序列 // \uddd Unicode序列 </script> ``` 1.9 处理textarea的单个行 ``` <textarea>123</textarea> <div id="result"></div> <input id="inputbox" value="456"> <script> var txtBox = document.getElementById("inputbox"); var lines = txtBox.value.split("\n"); var blk = document.getElementById("result"); blk.innerHTML = lines[lines.length-1]; </script> ``` 1.10 去除字符串末尾的空白 ``` <div id="test"></div> <script> var txtBox = document.getElementById("test"): var lines = txtBox.value.split("\n"); var resultString = ""; for(var i = 0;i < lines.length;i++){ var string = lines[i].trim(); resultString += string + "-"; } alert(resultString); </script> ``` 1.11 左补充或右补充一个字符串 ``` <div id="result"></div> <script> var preflinelength = 20; var oldStr = "this is a string"; var diff = preflinelength - oldStr.length; var filer = "&nbps;"; for(var i = 0;i < diff;i++){ oldStr = filer + oldStr; } document.getElementById("result").innerHTML = oldStr; </script> ```