Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove everything after the first instance of one of several characters

Say I have a string like:

var str = "Good morningX Would you care for some tea?"

Where the X could be one of several characters, like a ., ?, or !.

How can I remove everything after that character? If it could only be one type of character, I would use indexOf and substr, but it looks like I need a different method to find the position in this case. Perhaps a regular expression?

Clarification: I do not know what character X is. I'd like to cut the string off at the first occurrence of any one of the specified characters.

Ok, further clarification:

What I'm actually doing is scrubbing posts from a website. I'm taking the first bit from each post and stitching them together. By 'bit', I mean characters before the first piece of punctuation. I need to cut everything off after that punctuation. Does that make sense?

like image 397
Austen Avatar asked Oct 28 '25 01:10

Austen


1 Answers

Just replace everything within the [ and ] with your delimiters. Escape if necessary.

var str = "Good morning! Would you care for some tea?";
var beginning = str.split(/[.?!]/)[0];
// "Good morning"
like image 61
kalley Avatar answered Oct 30 '25 13:10

kalley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!