1

I have this string :

var author = "Tom Smith, Will Hughes, Adonis Young and Tyrek Hill";

And this is the function getNumOfAuthor :

function getNumOfAuthor(m_name:string) {
    const regex = /\s*(?:,|$)\s*/;
    var str = m_name.split(regex);
    alert(str.length);
    alert(str);
    if (str.length == 1) {
      num_of_author = 1;
    }
    else if (str.length > 1) {
      num_of_author = str.length;
    }

    return num_of_author;
  }

I want to use the split() method so that the full names are separated into elements in string array using regex as the split delimiter

Does anyone know what the regex would be? I can get comma working, but I can't seem to figure out how to have multiple punctuation and specific phrases working alongside it

1
  • 1
    I don't know about TypeScript, but can you just substitute ' and ' for a comma and split that? Snippet -> author.replace(/\sand\s/, ', ').split(/(?:,\s?)/) My output from your author variable is: ["Tom Smith", "Will Hughes", "Adonis Young", "Tyrek Hill"] Commented May 26, 2020 at 18:16

2 Answers 2

2

Two suggestions:

  1. Just count the number of , and and and add one.

  2. Split by , and and and count the length of the array.

var author = "Tom Smith, Will Hughes, Adonis Young and Tyrek Hill"

// First suggestion.
let authorCount = author.match(/(, )|( and )/).length + 1;
console.log("num of authors", authorCount);

// Second suggestion.
let authors = author.split(/, | and /)
console.log(authors, authors.length);

Sign up to request clarification or add additional context in comments.

Comments

1

Here's some scary regex for you to use.

const author = "Tom Smith, Will Hughes, Adonis Young and Tyrek Hill";

const regex = /,\s|and\s|(?<name>\w+\s\w+)/g

const result = [...author.matchAll(regex)]
  .map(pr => pr.groups || {
    name: null
  })
  .filter(pr => pr.name)
  .map(pr => pr.name)

console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.