简体   繁体   English

string.split 由于某种原因无法正常工作

[英]string.split is not working for some reason

I am trying to print the last name of the person "Michael" by splitting the string into an array and calling out the next word available.我试图通过将字符串拆分为数组并调用下一个可用单词来打印“迈克尔”人的姓氏。

When I run this code, I get undefined.当我运行这段代码时,我得到了未定义。 I tried using Pythontutor to see what am I doing wrong and it turns out that string.split() is not working.我尝试使用 Pythontutor 来查看我做错了什么,结果发现string.split()不起作用。

Can you please take a look and help figure me out what am I doing wrong?你能看看并帮我弄清楚我做错了什么吗?

Here is my code:这是我的代码:

 function getMichaelLastName(inputText) { var names = inputText; var newN = [names.split(" ")]; for (var i = 0; i<newN.length; i++) { if(newN[i] == "Michael") { var Michael = newN[i++]; } return Michael; } } console.log( getMichaelLastName("Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?") )

Your code has multiple issues:您的代码有多个问题:

  • Don't use newN[i++] because you're updating the i value.不要使用newN[i++]因为您正在更新i值。 Use newN[i+1] instead;改用newN[i+1]
  • You've got some scopes issues.你有一些范围问题。 You can learn more here: https://developer.mozilla.org/en-US/docs/Glossary/Scope您可以在这里了解更多信息: https://developer.mozilla.org/en-US/docs/Glossary/Scope
  • If the last word of the sentence was 'Michael', you'll get a overflow error ( newN[i+1] does not exist).如果句子的最后一个单词是 'Michael',你会得到一个溢出错误( newN[i+1]不存在)。
  • The split function already returns an array. split function 已经返回一个数组。

 function getMichaelLastName(inputText) { var names = inputText; var newN = names.split(" "); var michaelLastnames = [] for (var i = 0; i<newN.length - 1; i++) { if(newN[i] == "Michael") { michaelLastnames.push(newN[i+1]); } } return michaelLastnames; } var michaelLastname = getMichaelLastName("Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?") console.log(michaelLastname)

return words after Michael在迈克尔之后返回单词

function getMichaelLastName(inputText) {
  let newArr = []
  var names = inputText;
  var newN = names.split(" "); 
  for (var i = 0; i<newN.length; i++) {
    if(newN[i] === "Michael") {
      newArr = [...newArr, newN[i + 1]]
    }
  }
  return newArr
}

if you want return last name:如果你想返回姓氏:

function getMichaelLastName(inputText) {
  let newArr = ''
  var names = inputText;
  var newN = names.split(" "); 
  for (var i = 0; i<newN.length; i++) {
    if(newN[i] === "Michael") {
      newArr = newN[i + 1]
    }
  }
  return newArr
}

Regular Expression.正则表达式。 Search for word boundaries and Michael followed by Alphabetic word.搜索单词边界和 Michael,然后是字母单词。

interactive RegEx demo with explanations here: https://regex101.com/r/gC8tsi/2交互式正则表达式演示,此处有解释: https://regex101.com/r/gC8tsi/2
/\bMichael ([AZ][az]*?)\b/g is a regular expression literal (syntax is enclosed by / to indicate a regular expression). /\bMichael ([AZ][az]*?)\b/g是正则表达式文字(语法用/括起来表示正则表达式)。 Regular expressions are a pattern syntax designed for processing text with patterns.正则表达式是一种模式语法,用于处理带有模式的文本。
\b looks for word boundaries. \b查找单词边界。 Basically boundaries where it finds non-word elements.基本上是找到非单词元素的边界。
Michael_ just looks for that string. Michael_只是寻找那个字符串。
[AZ] looks for a uppercase letter [AZ]查找大写字母
[az]*? is a lazy sequence of lowercase letters (matches until the next word boundary \b )是小写字母的惰性序列(匹配到下一个单词边界\b

The map and slice at the end is just to slice off the first name from all found names. map 和最后的切片只是从所有找到的名称中切掉第一个名称。
||[] just returns an empty array for the case where no matches are found. ||[]仅在未找到匹配项的情况下返回一个空数组。

 function getMichaelLastName(inputText) { return (inputText.match(/\bMichael ([AZ][az]*?)\b/g)||[]).map(x=>x.slice('Michael '.length)) } console.log( getMichaelLastName("Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?") ) function getLastNames(inputText, name='Michael') { const rex = new RegExp(String.raw`\b${name} ([AZ][az]*?)\b`,'g') return (inputText.match(rex)||[]).map(x=>x.slice(name.length+1)) } console.log( getLastNames("Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?",'John'), getLastNames("Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?",'Michael') )

This code uses regex and capture the word (ie, potential lastname) after Michael<space>此代码使用正则表达式并在Michael<space>之后捕获单词(即潜在的姓氏)

const regex = /Michael (\w+)/gm;
const str = "Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?";
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

 function getMichaelLastName(inputText) { var Michaels = []; var names = inputText; var newN = names.split(' '); for (var i = 0; i < newN.length; i++) { const x = newN[i]; if (x.includes( "Michael")) { if(newN[i+1].length>3) Michaels.push(newN[i + 1].replace('?','')); } } return Michaels; } console.log( getMichaelLastName("Michael, how are you? - Cool, how is John Williamns and Michael Jordan? I don't know but Michael Johnson is fine. Michael do you still score points with LeBron James, Michael Green AKA Star and Michael Wood?") )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM