On some basic algorithms of characters and numbers in JS _javascript skills

Source: Internet
Author: User
Tags lowercase alphanumeric characters

Recently in the brush FCC problem, as the upgrade hit strange, a close to the past, but also quite attracted me. Today take time to Basic algorithm scritping This part of the problem, according to some hints, or relatively simple. Some problems to deal with the way, I think it is worth learning. For example, in the project sometimes to deal with a character, if you do not think of some relevant methods, it is very troublesome, so, in this record, if you encounter some characters or array processing, can be turned over this article, hoping to get some tips instead of going to the document.

See this blog Bo friends, there are better and simpler code or good ideas, please message exchange (I always feel that only learn from other people's good code can progress faster, more flexible thinking). For beginners, don't look at the code and try to do it again. (The following topics do not consider the parameter type, strictly should be the parameter type to make a judgment, eg:typeof (arg) = = number)

1.Reverse a String

Flip a string

The string is converted into arrays, then the array is flipped by the reverse method of the array, and finally the array is converted to a string.

Your results must be a string.

function ReverseString (str) {
 str = str.split ("). Reverse (). Join (");
 
 return str;
}

ReverseString ("Hello");

2.Check for Palindromes

Returns true if the given string is a palindrome, and returns false instead.

If a string ignores punctuation, capitalization, and spaces, reads and reads exactly the same, then the string is Palindrome (palindrome).

Note that you need to remove the extra punctuation and whitespace from the string, and then convert the string to lowercase to verify that the string is a palindrome.

The value of the function argument can be "racecar", "racecar", and "race car".

function Palindrome (str) {
 //good luck!
 
 Str=str.replace (/[\ |\~|\ ' |\!| \@|\#|\$|\%|\^|\&|\*|\ (|\) |\-|\_|\+|\=|\| | \\|\[|\]|\{|\}|\;|\:|\ "|\ ' |\,|\<|\.| \>|\/|\?] /g, ""); Remove punctuation marks, this is my Baidu, JS is not very familiar with
 str = str.replace (/\s+/g);
 str = Str.tolowercase ();
 var arr = str.split (');
   arr = Arr.reverse ();
  var str1 = Arr.join ("");
 if (str = = str1) {return
 true;}
 return false;
}



Palindrome ("Eye");

/* Palindrome ("eye") should return a Boolean value
palindrome ("eye") should return true
. Palindrome ("race car") should return true.
Palindrome ("Not a palindrome") should return false.
Palindrome ("A man, a plan, a canal.") Panama ") should return true.
Palindrome ("Never odd or even") should return true.
Palindrome ("nope") should return false.
Palindrome ("Almostomla") should return false.
Palindrome ("My age is 0, 0 si ega ym.") should return true.
Palindrome ("1 eye for 1 eye.") should return false.
Palindrome ("0_0" (:/-\:) 0-0 ") should return true.



*/

3.Title case a sentence

Make sure that the first letter of each word in the string is capitalized and the remainder is lowercase.   (Eg:titlecase ("I ' m a little tea pot") should return "I ' m a little tea pot". Titlecase ("Short and sToUt") should return "short and sToUt".

/* This topic is very simple, mainly to understand that split () is to split the string into a group 
join () is the array into a string 
toLowerCase () touppercase () case conversion, note that only the letter valid, other characters (eg:/,!@ Invalid

/function Titlecase (str) {
 str = str.split ("");//Divide the string into groups by space for
  (var i = 0; i < str.length; i++) {
    Str[i] = Str[i].tolowercase ();
    Str[i] = str[i].substring (0, 1). toUpperCase () + str[i].substring (1);
  }
  Return Str.join ("");//concatenate array into string by Space
}

titlecase ("I ' m a Little tea pot");

4.Confirm the ending

Checks whether a string (str) ends with the specified string (target).

Returns True if it is, or false if it is not. For example: confirmending ("Bastian", "n") should return true.  confirmending ("Connor", "n") should return to false.  confirmending (" Walking on water and developing software from a specification are easy if both are "" Frozen ") should return to specification r>

function confirmending (str, target) {
 //"Never give up and good luck'll find you."
 --Falcor return
 
 str.substr (str.length-target.length) = = Target true:false;
}

Confirmending ("Bastian", "n");
Confirmending ("He has to give me a new name", "NA");
/* confirmending ("Bastian", "n") should return true.
Confirmending ("Connor", "n") should return false.
Confirmending ("Walking on water and developing software from a specification are easy if both are frozen", "specification" should return false.
Confirmending ("He has to give me a new name", "name") should return true.
Confirmending ("He has to give me a new name", "Me") should return true.
Confirmending ("He has to give me a new name", "NA") should return false.
Confirmending ("If you are want to save my world, you must hurry." We dont know how much longer we can withstand the ' nothing ', ' mountain ' should return false.
*/

5.Repeat A string Repeat a string

The important thing to say 3 times!

Repeats a specified string of num times, and returns an empty string if num is a negative number. For example:

Repeat ("*", 3) should return "* * *".
Repeat ("ABC", 3) should return "ABCABCABC".
Repeat ("ABC", 4) should return "ABCABCABCABC".
Repeat ("abc", 1) should return "ABC".
Repeat ("*", 8) should return to "********".
Repeat ("ABC",-2) should return "".

When you can not complete the challenge, remember to open a big recruit ' read-search-ask '.

Here are some resources that are helpful to you:

Global String Object

function repeat (str, num) {
 //repeat after me
 var newstr = str;
 if (num >1) {for
  (var i = 1; i< num i + +) {
   str +=newstr;
  }
  return str;
 } else if (num = = 1) {return
  str;
 } else{return
  "";
 }

Repeat ("ABC", 3);
Repeat ("*", 3);

6.Chunky Monkey

Monkeys eat bananas but break into several paragraphs to eat Oh!

Divides an array arr by the specified size of the array to a number of blocks.

For example: Chunk ([1,2,3,4],2) =[[1,2],[3,4]];

Chunk ([1,2,3,4,5],2) =[[1,2],[3,4],[5]];

function chunk (arr, size) {
 //Break it up.
var arr1 = [];
  for (var i = 0; i < arr.length i = i + size) {
    var arr2 = arr;
    Arr1.push (Arr2.slice (i, i + size));
  }
  return arr1;
}

Chunk (["A", "B", "C", "D"], 2);

7.Falsy Bouncer

The True Monkey King!

Deletes all false values from the array.

In JavaScript, false values are false, NULL, 0, "", Undefined, and Nan.

When you can not complete the challenge, remember to open a big recruit ' read-search-ask '.

Here are some resources that are helpful to you:

Boolean Objects
Array.filter ()

For example:

Bouncer ([7, "ate", "", false, 9]) should return [7, ate, 9].

Bouncer (["A", "B", "C"]) should return ["a", "B", "C"].

Bouncer ([False, NULL, 0, NaN, Undefined, "]) should return [].

Bouncer ([1, NULL, NaN, 2, undefined]) should be returned [1, 2].

* * 
This topic is the understanding of the filter, this is my first code, write is not very good, not much reference value
also pay attention to NaN comparison. Oneself is not equal to oneself (NaN!) = NaN)
*

/function Bouncer (arr) {
 //Don ' t show a false ID to this bouncer.
 var arr1 =[];
  var j = 0;
  Arr.filter (function (val, index) {
    if (val = = False | | val = = NULL | | val = = 0 | | | val = = "" "| | val = = Undefined | | Val!== val) {
      Arr1.push (index);
    }
  });
  var len = arr1.length;

  for (var i = 0; i < len; i++) {
     arr.splice (arr1[i]-j,1);
     j + +;
  }
 return arr;
}

Bouncer ([7, "ate", "", false, 9]);

8.Seek and Destroy

Jinx's Mortar!

Implement a Destroy (destroyer) function, the first parameter is the array to be destroyed, and the rest of the parameters are values to be destroyed.

For example:

Destroyer ([1, 2, 3, 1, 2, 3], 2, 3) should be returned [1, 1].
Destroyer ([1, 2, 3, 5, 1, 2, 3], 2, 3) should be returned [1, 5, 1].
Destroyer ([3, 5, 1, 2, 2], 2, 3, 5) should be returned [1].
Destroyer ([2, 3, 2, 3], 2, 3) should be returned [].
Destroyer (["Tree", "Hamburger",], "tree", 53) should return ["Hamburger"].

Here are some resources that are helpful to you:

arguments Object
Array.filter ()

Function Destroyer (arr) {
 //Remove all the values
 var temparguments = arguments;
 Return Arr.filter (function (entry) {for
  (var i = 1; i< temparguments.length; i++) {
   if (entry = = Temparguments[i ]) {return
    false;
   }
  }
  return true;
 });

Destroyer ([1, 2, 3, 1, 2, 3], 2, 3);

9.Where do I belong

Where am I?

The array is sorted first, then the specified value is positioned in the array, and the corresponding index is returned.

For example: where ([1,2,3,4], 1.5) should return 1. Since 1.5 is inserted into [1,1.5,2,3,4] after the array [1,2,3,4], and the 1.5 corresponding index value is 1.

Similarly, where ([20,3,5], 19) should return 2. Because the array is sorted first [3,5,20],19 inserted into the array [3,5,20] and then [3,5,19,20], the corresponding index value of 19 is 2.

Here are some resources that are helpful to you:

Array.Sort ()

The function where (arr, num) {//Find me place in this
 sorted array.
 Note Sort () Collation
 arr.sort (function (a,b) {return
   a-b;
 });

 for (var i =0;i<arr.length;i++) {
   
  if (arr[i]>num | arr[i] = = num) {return
    
   i;
  }
 }
 return arr.length;
}



where ([5, 3, 20, 3], 5);

10.Caesars Cipher

Let God be God, Caesar's Caesar.

Here we introduce the world's most popular Caesar password Caesar cipher, also known as the shift password.

The shift cipher, or the letter in the cipher, is shifted according to the specified number.

A common case is the ROT13 cipher, which shifts 13 positions. By ' A ' ↔ ' N ', ' B ' ↔ ' O ', and so on.

Write a ROT13 function that implements the input encryption string and outputs the decryption string.

All letters are uppercase, do not convert any non-alphanumeric characters (for example: spaces, punctuation marks), encounter these special characters, skip them.

For example:

ROT13 ("SERR pbqr pnzc") should be decoded as "free CODE CAMP"

ROT13 ("SERR cvmmn!") should be decoded to "free pizza!"

ROT13 ("SERR Ybir?") should be decoded as "free love?"

ROT13 ("GUR dhvpx oebja qbt whzcrq bire GUR ynml SBK.") should be decoded to "the QUICK BROWN DOG jumped over the LAZY FOX."

Here are some resources that are helpful to you:

String.charcodeat ()
String.fromCharCode ()

function rot13 (str) {//LBH qvq vg!
  var arr = Str.touppercase (). Split ("");
  var str1 = [];
  for (var i = 0; i < arr.length i++) {
    var arr1 = Arr[i].split ("");
    for (var j = 0; J < Arr1.length; J + +) {
      var num = arr1[j].charcodeat ();
      if (num >= && num <=) {
        arr1[j] = num + > 90? String.fromCharCode (+ (num + 13-90)): String.fromCharCode (num + 13); The + (num + 13-90) To understand why is the,
      }
    Str1.push (Arr1.join (""));
  Return Str1.join ("");
}

Change the inputs below to test
rot13 ("SERR pbqr pnzc");

The above article on JS characters and numbers in some basic algorithms is to share the whole of the content of everyone, hope to give you a reference, but also hope that we support the cloud-dwelling community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.