开发者

Needing to do some pattern matching with javascript

开发者 https://www.devze.com 2023-03-31 02:52 出处:网络
I have a long string that a user entered. Using javascript I want to get the text of the first sentence IF it ends in a question mark. Is there a simple way I can do this?

I have a long string that a user entered. Using javascript I want to get the text of the first sentence IF it ends in a question mark. Is there a simple way I can do this?

For example:

var myText1 = "What is your name? My name is Michelle."

I need to return: "What is your name"

var myText2 = "this is a test. this is a test开发者_如何学Go."

I need to return: "n/a"


Regex to the rescue:

var res = str.match(/^([^.]+)\?/);
var output = (res == null) ? 'n/a' : res[1];


I'm confused as to how practical this would be, but this should work.

var text = "this is a question? this is some text.";

var split1 = text.split(/[.?]+/); // splits the text at "." and "?"
var split2 = text.split(/[?]+/); // splits the text at "?"


// if the first element in both arrays is the same, the first sentence is a question.
var result = (split1[0] == split2[0]) ? split1[0] : "n/a";


According to US English grammar rules, sentences end in ., ? or !, but if the sentence ends in a quotation then a " will follow (He said to me, "How are you doing?"). Does this count as a question? The sentence itself is a statement quoting a question, so I'll assume the answer is no. This makes it easier since we only have to account for ? not followed by a ".

Given the above, here's my solution:

function startIsQuestion( str ) {
  var m = str.match(/^[^.!]+[?][^"]/);
  if (!m || 
      m[0].indexOf('.') >= 0 ||
      m[0].indexOf('!') >= 0 ||
      m[0].indexOf('?"') >= 0) return "n/a";
  return m[0];
}

I don't think it's completely robust, but I'm not sure of your complete requirements and it should give you a good start.

See demo

0

精彩评论

暂无评论...
验证码 换一张
取 消