Given a string, for example: "abaasdffggghhjjkkgfddsssss3444343";
1, the byte length of the string
Reference code:
document.write (txt.length+ "<br/>");d ocument.write ("<br/>");
2. Remove the characters from the specified position, such as: 0,3,5,9, etc.
Reference code:
for (Var i=0;i<txt.length;i++) { if (i==0 | | i==3 | | i==5 | | i==9) { document.write ("The position is" +i+ "character is:" +txt.substr ( i,1) + "<br/>");} } document.write ("<br/>");
3. Find out whether the specified character exists in the above string, such as: I,c, B, etc.
Reference code:
if (Txt.indexof ("I")!=-1) { document.write ("I exist in string <br/>");} else{ document.write ("I do not exist in string <br/>");} if (Txt.indexof ("C")!=-1) { document.write ("C exists in string <br/>");} else{ document.write ("C does not exist in string <br/>");} if (Txt.indexof ("B")!=-1) { document.write ("b exists in string <br/>");} else{ document.write ("B does not exist in string <br/>");}
4, replace the specified characters, such as: g Replace with 22,SS to replace with B and other methods of operation
Reference code:
document.write (TXT); var txtreg=/[g]/g; The use of regular expressions Var txtvalue=txt.replace (Txtreg, "a");d ocument.write ("<br/>");d ocument.write (txtvalue); document.write ("<br/>");d ocument.write ("<br/>");d ocument.write (TXT); var txtreg=/[s]{2}/g;var Txtvalue=txt.replace (Txtreg, "B");d Ocument.write ("<br/>");d ocument.write (txtvalue);d ocument.write ("<br /> ");
5. Find the most occurrences of the characters in the above string and the number of occurrences
Reference code:
var json = {};for (var i=0;i<txt.length;i++) { if (!json[txt.charat (i)]) { Json[txt.charat (i)] = 1; } else { Json[txt.charat (i)]++; }} var char= '; var num=0;for (var key in JSON) { if (json[key]>num) { char = key; num = Json[key];} } document.write (txt+ "The most occurrences of the character is" +char+ "and the number of times is:" +num);
Common actions for JavaScript to handle strings