Austen
Austen

Reputation: 1970

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?

Upvotes: 4

Views: 5552

Answers (4)

codebreaker
codebreaker

Reputation: 1485

The below code will do as you expect:

 var s = "Good morningX Would you care for some tea?";
  s = s.substring(X, n != -1 ? n : s.length);
  document.write(s);

Upvotes: 0

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38683

Try this, If the X have this ',' character , then try below

var s = 'Good morning, would you care for some tea?';
s = s.substring(0, s.indexOf(','));
document.write(s);

Demo : http://jsfiddle.net/L4hna/490/

and if the X have '!' , then try below

var s = 'Good morning! would you care for some tea?';
s = s.substring(0, s.indexOf('!'));
document.write(s);

Demo : http://jsfiddle.net/L4hna/491/

Try this way for your requirement string.

Both are will return Good Morning

Upvotes: 1

xiankai
xiankai

Reputation: 2781

http://jsfiddle.net/JEFnY/

The regex would be

str.replace(/(.*?)([\.\?\!])(.*)/i, '$1$2');

The first capturing group is a lazy expression to match everything before the next capturing group.

The second capturing group only looks for the characters that you specify - which in this case are .!?, all escaped.

The last capturing group is discarded. Hence the substitution string is $1$2, or the first two capturing groups together.

Upvotes: -1

kalley
kalley

Reputation: 18462

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"

Upvotes: 7

Related Questions