如何在JavaScript中选择数组中的特定字符而不使用正则表达式?

huangapple go评论68阅读模式
英文:

How can I select specific characters in an array without using RegEx in Javascript?

问题

我正在做多个编程挑战,以加入编程训练营,但在同一个问题上卡了几天。

我已经在网上查找了信息,尝试了不同的解决方案,但似乎无法通过他们控制台上的特定测试。

指令

创建一个名为extractPassword的函数,该函数接受一个字符数组(包括一些垃圾字符),并返回一个只包含有效字符(a-z,A-Z,0-9)的字符串。

这是一个示例:

extractPassword(['a', '-', '~', '1', 'a', '/']); // 应返回字符串 'a1a'
extractPassword(['~', 'A', '7', '/', 'C']); // 应返回字符串 'A7C' 

尝试1:

首先,我尝试使用正则表达式:

var newArray = [];

var extractPassword = function(arr){
    // 在这个区域,我展示了数组:
 
    console.log('arr: ' + arr);
    
    // 在这里,我将数组转换为一个字符串,然后使用带有“g”的正则表达式参数的.match()方法来查找匹配项,以便不止在第一次匹配后停止:
    return arr.join('').match(/[a-zA-Z0-9]/g);
};

console.log(extractPassword(['a', '-', '~', '1', 'a', '/']).toString().replace(/,/g, ''));

最终结果是我想要的:a1a

但在他们的程序上输出错误消息:
>>>代码不正确,正则表达式很酷,但这不是我们要找的解决方案的类型。

尝试2:

然后,我尝试将一个函数与一个for循环和一个if语句结合起来:

var newArray = [];

extractPassword(['a', '-', '~', '1', 'a', '/']);

//extractPassword(['~','A','7','/','C']);

function extractPassword(arr){
    // 在这里,我将数组记录到控制台,以确保将正确的值传递给函数:
    console.log('arr: ' + arr);
    
    // 在这里,我将数组转换为一个字符串,并将其值记录到arrayToString变量中,以确保我显示了我想要的字符串:
    var arrayToString = arr.join('');
    
    // 在这里,我将arrayToString变量的值记录到控制台,以确保我显示了我想要的字符串:
    console.log('arrayToString: ' + arrayToString);
    
    // 在这里,我将使用for循环来迭代字符串的字符,并创建charCode变量,该变量将使用charCodeAt()方法将arrayToString变量的每个元素(i)转换为Unicode值:
    
    for (var i = 0; i < arrayToString.length; i++){
        var charCode = arrayToString.charCodeAt(i);
        // 在这里,我记录不同的arrayToString变量的i元素以及其charCode值:
        console.log('charCode ' + i + ': ' + charCode);
        
        // 在这里,我将插入一个条件来表示:“如果我们有一个字符在a和z之间,或在A和Z之间,或在0和9之间,将这些字符推送到newArray中”:
        
        if((charCode > 47 && charCode < 58) || (charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123)){
            newArray.push(arr[i]);
            console.log('newArray: ' + newArray);
        }
        
    }

    console.log('最终字符串: ' + newArray.join(''));
}

这里给我的结果是a1a,但控制台仍然给我一个错误:>>>代码不正确。您的函数没有返回正确的值。

是否有其他方式来完成他们的要求?我尝试了一些其他方法,但我已经卡了很长时间,无法解决问题。

英文:

I am doing multiple coding challanges to join a coding bootcamp but have been stuck at the same problem for a few days now.

I have looked online, tried differen solutions, but nothing seems to pass their specific test on their console.

Instructions

Create a function named extractPassword which takes an array of characters (which includes some trash characters) and returns a string with only valid characters (a - z, A - Z, 0 - 9).

Here's an example:

extractPassword([&#39;a&#39;, &#39;-&#39;, &#39;~&#39;, &#39;1&#39;, &#39;a&#39;, &#39;/&#39;]); // should return the string &#39;a1a&#39;
extractPassword([&#39;~&#39;, &#39;A&#39;, &#39;7&#39;, &#39;/&#39;, &#39;C&#39;]); // should return the string &#39;A7C&#39; 

TRY 1:

I first tried using a RegEx:

var newArray = [];

var extractPassword = function(arr){
    //in this area I display the array:
 
    console.log(&#39;arr: &#39; + arr);
    
    //here I transformed the array into a string with the method .join() and then looked for a match with the method .match() with the parameter of a RegExp with a g at the end so it doesn&#39;t stop after the first match:
    return arr.join(&#39;&#39;).match(/[a-zA-Z0-9]/g);
};

console.log(extractPassword([&#39;a&#39;,&#39;-&#39;,&#39;~&#39;,&#39;1&#39;,&#39;a&#39;,&#39;/&#39;]).toString().replace(/,/g, &#39;&#39;));

The end result is what I wanted: a1a

But the output on their programe gave me an error:
>>>Code is incorrect RegExs are cool, but that is not the type of solution we are looking for.

TRY 2
Then, I tried combining a function with a for loop and an if statement:

var newArray = [];

extractPassword([&#39;a&#39;,&#39;-&#39;, &#39;~&#39;, &#39;1&#39;, &#39;a&#39;, &#39;/&#39;]);

//extractPassword([&#39;~&#39;,&#39;A&#39;,&#39;7&#39;,&#39;/&#39;,&#39;C&#39;]);

function extractPassword(arr){
    //here I console.log the array, to ensure I am passing the right value to the function:
    console.log(&#39;arr: &#39; + arr);
    
    //Here I atribute the array transformed into a string to the var arrayToString:
    var arrayToString = arr.join(&#39;&#39;);
    
    //Here I console.log the value of the var arrayToString to ensure I am displaying what I want: a string:
    
    console.log(&#39;arrayToString: &#39; + arrayToString);
    
    //Here I will use a for loop to iterate through the characters of the string, and create the var charCode, which will transform each element of the arrayToString var (i) into a Unicode value with the method charCodeAt():
    
    for (var i = 0; i &lt; arrayToString.length; i++){
        var charCode = arrayToString.charCodeAt(i);
        //Here I console.log the different i elements of the arrayToString variable and also its charCode value:
        console.log(&#39;charCode &#39; + i + &#39;:&#39; + charCode);
        
        //Here I will insert a condition to say: &#39;If we have a character between a and z OR A and Z OR 0 and 9, push those characters into the newArray&#39;:
        
        if((charCode &gt; 47 &amp;&amp; charCode &lt; 58) || (charCode &gt; 64 &amp;&amp; charCode &lt; 91) || (charCode &gt; 96 &amp;&amp; charCode &lt; 123)){
            newArray.push(arr[i]);
            console.log(&#39;newArray: &#39; + newArray);
        }
        
    }

    console.log(&#39;Final string: &#39; + newArray.join(&#39;&#39;));
}

The result that gives me here is a1a, but the console still gives me an error: >>Code is incorrect. Your function is not returning the correct value.

Does anyone have an alternative way to do what they ask for? I have tried a few other things, but I've been at this for so long, I can's get unstuck.

答案1

得分: 1

看起来你想使用.filter()方法来去掉数组中不在范围0-9A-Za-z内的字符。然后你可以在结果数组上调用.join()方法。像这样:

const extractPassword = arr => arr.filter(ch => (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')).join('');

console.log(extractPassword(['a', '-', '~', '1', 'a', '/'])); // 应该返回字符串 'a1a'
console.log(extractPassword(['~', 'A', '7', '/', 'C'])); // 应该返回字符串 'A7C'

请注意,你可以将字符与其他字符进行比较,不需要调用.charCodeAt()然后与ASCII值进行比较。

英文:

It looks like you want to use the .filter() method to get rid of any character in the array that isn't within the ranges 0-9, A-Z, and a-z. You can then just call .join() on the resulting array. Like this:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const extractPassword = arr =&gt; arr.filter(ch =&gt; (ch &gt;= &#39;0&#39; &amp;&amp; ch &lt;= &#39;9&#39;) || (ch &gt;= &#39;A&#39; &amp;&amp; ch &lt;= &#39;Z&#39;) || (ch &gt;= &#39;a&#39; &amp;&amp; ch &lt;= &#39;z&#39;)).join(&#39;&#39;);

console.log(extractPassword([&#39;a&#39;, &#39;-&#39;, &#39;~&#39;, &#39;1&#39;, &#39;a&#39;, &#39;/&#39;])); // should return the string &#39;a1a&#39;
console.log(extractPassword([&#39;~&#39;, &#39;A&#39;, &#39;7&#39;, &#39;/&#39;, &#39;C&#39;])); // should return the string &#39;A7C&#39;

<!-- end snippet -->

Note that you can compare the character with other characters; you don't have to call .charCodeAt() and then compare it with ASCII values.

答案2

得分: 1

要做到这一点而不使用正则表达式,您可以创建一个使用String.codePointAt()Array.filter()的函数,并将该过滤器应用于已经以数组形式提供给您的输入。

const firstCodePoint = 48; // 'A'
const lastCodePoint = 122; // '9'

const isAlphaNumeric = (character) => {
  const thisCodePoint = character.codePointAt(0);
  return (thisCodePoint >= firstCodePoint) && (thisCodePoint <= lastCodePoint);
};

const extractPassword = (arr) => {
  const filteredString = arr.filter(isAlphaNumeric).join("");
  return filteredString;
};

console.log( extractPassword(['a', '-', '~', '1', 'a', '/']) ); // 'a1a'
console.log( extractPassword(['~', 'A', '7', '/', 'C']) ); // 'A7C';

请注意,以上是提供的代码的翻译部分。

英文:

To do this without Regex, you could create an Array.filter() that leverages String.codePointAt(), and apply that filter to your inputs, which were conveniently provided to you already in array form.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const firstCodePoint = 48; // A
const lastCodePoint = 122; // 9

const isAlphaNumeric = (character) =&gt; {
  const thisCodePoint = character.codePointAt(0);
  return (thisCodePoint &gt;= firstCodePoint) &amp;&amp; (thisCodePoint &lt;= lastCodePoint);
};

const extractPassword = (arr) =&gt; {
  const filteredString = arr.filter(isAlphaNumeric).join(&quot;&quot;);
  return filteredString;
};

console.log( extractPassword([&#39;a&#39;, &#39;-&#39;, &#39;~&#39;, &#39;1&#39;, &#39;a&#39;, &#39;/&#39;]) ); // &#39;a1a&#39;
console.log( extractPassword([&#39;~&#39;, &#39;A&#39;, &#39;7&#39;, &#39;/&#39;, &#39;C&#39;]) ); // &#39;A7C&#39;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月27日 00:41:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75573477.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定