Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Kiểm tra chuỗi có bắt đầu bằng dấu câu trong JavaScript


Giả sử có hai chuỗi, một trong số chúng bắt đầu bằng dấu hỏi (dấu câu):

var sentence1 = 'My Name is John Smith.' var sentence2 = '? My Name is John Smith.'

Cần kiểm tra xem câu nào bắt đầu bằng dấu câu. Sử dụng biểu thức chính quy.

Ví dụ

var punctuationDetailsRegularExpression=/^[.,:!?]/ var sentence1 = 'My Name is John Smith.' var output1 = !!sentence1.match(punctuationDetailsRegularExpression) if(output1==true) console.log("This ("+sentence1+") starts with a punctuation"); else console.log("This ("+sentence1+") does not starts with a punctuation"); var sentence2 = '? My Name is John Smith.' var output2 = !!sentence2.match(punctuationDetailsRegularExpression) if(output2==true) console.log("This ( "+sentence2+") starts with a punctuation"); else console.log("This ( "+sentence2+" ) does not starts with apunctuation");

Chạy: node fileName.js. File demo209.js.

Kết quả

PS C:\Users\Amit\javascript-code> node demo209.js This (My Name is John Smith.) does not starts with a punctuation This ( ? My Name is John Smith.) starts with a punctuation