JS: remove end of string after nth character of type

I'm trying to write a script to remove the end of a string after a user inserts a number of special characters.

An example would be: Remove the end of a string from the 3rd comma, including the 3rd comma, so:

// Hi, this, sentence, has, a, lot, of commas

would become:

// Hi, this, sentence

I haven't been able to accomplish this with indexOf() because I don't know where the 3rd comma will occur in the sentence and I don't want to use split because that would create a break at every comma.

Upvotes: 0

Views: 1533

Answers (2)

Cerbrus
Cerbrus

Reputation: 72857

You can use split/slice/join to get the desired part of the string:

const str = "Hi, this, sentence, has, a, lot, of commas";
const parts = str.split(",");
const firstThree = parts.slice(0,3);
const result = firstThree.join(",");

console.log(result, parts, firstThree);

In a one-liner, that would be:

const result = str.split(",").slice(0,3).join(",");

Another simple option would be a regex:

const str = "Hi, this, sentence, has, a, lot, of commas";
const match = str.match(/([^,]+,){3}/)[0]; // "Hi, this, sentence,"
console.log(match.slice(0, -1));

This one uses the string variant of slice.

This is how the regex works:

  • In a capturing group (),
  • Find me at least one (+) character that is not a comma ([^,]): [^,]+
  • Followed by a comma ,
  • Now give me 3 of those groups after each other {3}

Upvotes: 3

baao
baao

Reputation: 73221

You can use below regex to get the result

const str = 'Hi, this, sentence, has, a, lot, of commas';
const m = str.match(/^(?:[^,]*,){2}([^,]*)/)[0];
console.log(m);

Upvotes: 0

Related Questions