JS函数从2个字符串中返回匹配的字母

时间:2019-02-10 15:01:28

标签: javascript

该函数返回用户通过两个字符串提交的首个字母     输入文本,字符串之间用逗号分隔。例如:aaaaa,bbbbba->匹配的字母为'a',因为两个字符串中都存在 抱歉有些意大利名字,但我用意大利语编码

我不确定如何继续,我有一个可以同时使用两个字符串的方法,但是我不确定是否正确

function Ripetizione() {
  var rip = document.getElementById("string").value;
  if (rip.indexOf(",") == -1) { //check to see if the comma is not present
    alert("Non c'è nessuna virgola");
    return;
  }

  var stringa1 = rip.substr(0, rip.indexOf(",")); //this is the string1 before the comma
  var stringa2 = rip.substr(rip.indexOf(",") + 1, rip.length - (stringa1.length + 1)); //this is the second string after the comma

  for (i = 0; i <= stringa1.length; i++) { //for cycle to count the elements of the first string


  }


  for (k = 0; i <= stringa2.lenght; k++) { //same for the string2

  }
}

Ripetizione()

7 个答案:

答案 0 :(得分:2)

您无需循环第二个字符串。只需在循环遍历第一个字符串部分的每个元素时检查元素的索引=> 0即可。并返回值。

答案 1 :(得分:2)

总是比命令式编程更喜欢功能。使用Array#find

function getCommonLetter(str){
const [stringA, stringB]=str.split(',');
return Array.from(stringB).find(val => stringA.includes(val));
}

console.log(getCommonLetter('ab,ba'))
console.log(getCommonLetter('ads,bsd'))
console.log(getCommonLetter('aaa,bbc'))

答案 2 :(得分:1)

function Ripetizione() { 
    var rip=document.getElementById("string").value;
    if (rip.indexOf(",")==-1){
        alert("Non c'è nessuna virgola");
        return;
    }

    var stringa1=rip.substr(0,rip.indexOf(","));
    var stringa2=rip.substr(rip.indexOf(",")+1,rip.length-(stringa1.length+1));

    return search(stringa1, stringa2);
}

function search(a, b){
    for(var i=0; i<a.length;i++){
        for(var j=0;j<b.length;j++){
            if(a[i] == b[j]){
                return a[i];
            }
        }
    }
}

答案 3 :(得分:0)

我们可以使用Array#reduce进行操作,并使用Array#includes检查是否存在匹配的字符。

这个想法是使用Array#from将字符串转换为字符串数组,然后使用reduce函数来匹配并累积匹配的字符。

//returns the matching chars as an array
function Ripetizione(rip) { 
  //let rip=document.getElementById("string").value;
  let strs = rip.split(",");
  if (strs.length !== 2){ //check to see if the comma is not present
      alert("Non c'è nessuna virgola");
      return;
  }
  //converting strings to array to use reduce
  let strOne = Array.from(strs[0]), strTwo = strs[1];
  return strOne.reduce((acc,alpha)=> {
    return !acc.includes(alpha) && strTwo.includes(alpha)?[alpha,...acc]:acc;
    },[]).slice(0,1).toString();
}
console.log(Ripetizione("aaaaaab,bbbbba"));
console.log(Ripetizione("aaaaaa,bbbbba"));
console.log(Ripetizione("acccaaaa,bbbbba"));
console.log(Ripetizione("acccaaaa,bbbbcba"));
console.log(Ripetizione("dddddddd,bbbbba")); //return blank string
console.log(Ripetizione("ab,ba"));

答案 4 :(得分:0)

@client.event
async def on_message(message):
    channel = message.channel
    if 'donate' in message.content:
        await client.send_message(channel, 'To donate click this link http://www.test.com')
         function Ripetizione() {
var rip = document.getElementById("string").value;
if (rip.indexOf(",") == -1) { //check to see if the comma is not present
    alert("Non c'è nessuna virgola");
    return;
}

var stringa1 = rip.substr(0, rip.indexOf(",")); //this is the string1 before the comma
var stringa2 = rip.substr(rip.indexOf(",") + 1, rip.length - (stringa1.length + 1)); //this is the second string after the comma

if (stringa1.length <= stringa2.length) {
    stringa2 = stringa2.split('')
    stringa1 = stringa1.split('')

    for (i = 0; i <= stringa2.length; i++) { //for cycle to count the elements of the first string
        if (stringa1.includes(stringa2[i])) {
                console.log(stringa2[i]);
          
        }

    }
} else if (stringa1.length >= stringa2.length) {
    stringa1 = stringa1.split('')
    stringa2 = stringa2.split('')
    for (i = 0; i <= stringa1.length; i++) { //for cycle to count the elements of the first string
        if (stringa2.includes(stringa1[i])) {
                console.log(stringa1[i]);
            
        }
    }
}
}

答案 5 :(得分:0)

以下演示将change事件绑定到输入。当用户在输入中输入文本,然后在输入之外单击时,将调用该函数。该函数使用split()filter()并将结果显示在输出中。该功能还会删除所有空格,并在没有匹配项时报告。

演示

详细信息在演示中被评论

var str = document.getElementById("string");

// This is an Event Handler
function ripZ(e) {
  var result = document.getElementById('result');
  var rip = this.value;
  if (rip.indexOf(",") === -1) {
    result.value = "Separate the two strings with a comma (no spaces).";
    return;
  }

  // If there's a space remove it
  var rip = rip.replace(/\s/g, '');

  // Split the string at the comma making an array of two strings
  var array = rip.split(',');

  /*
  Take each string and split them at each letter.
  Now there's two arrays of letters
  */
  var first = array[0].split('');
  var second = array[1].split('');

  /*
  Loop through both arrays by using two for...of loops
  */
  var match = first.filter(function(f, i) {
    return second.indexOf(f) !== -1;
  });

  // Display results
  if (match) {
    result.innerHTML = `
The letter "${match[0]}" is the first match between both strings.`;
  } else {
    result.value = "There was no match."
  }
  return;
}

/* 
This is an onevent property registered to the input
If a user types into the input then clicks outside of input
the Event Handler ripZ() is called.
*/
str.onchange = ripZ;
<input id='string'><button>GO</button><br>
<output id='result'></output>

答案 6 :(得分:0)

如果输入的是“ ab,ba”,您很难过它应该返回b,因此代码必须在我的开头:

function Ripetizione() { 
  //  var rip=document.getElementById("string").value;
  //  if (rip.indexOf(",")==-1){
  //      alert("Non c'è nessuna virgola");
  //      return;
  //  }

  //  var stringa1=rip.substr(0,rip.indexOf(","));
  //  var stringa2=rip.substr(rip.indexOf(",")+1,rip.length-(stringa1.length+1));
var stringa1="ab";
var stringa2="ba";

for(var i=0; i<stringa2.length;i++){
    for(var j=0;j<stringa1.length;j++){
        if(stringa2.charAt(i) === stringa1.charAt(j)){
            console.log(stringa2.charAt(i));
            return;
        }
    }
}