Let’s say we have the following strings. One of them is beginning with a question mark i.e. punctuation −
var sentence1 = 'My Name is John Smith.' var sentence2 = '? My Name is John Smith.'
We need to check whether any of the above two sentences begin with punctuation. To check if string begins with punctuation, the code is as follows −
Example
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");
To run the above program, you need to use the following command −
node fileName.js.
Here my file name is demo209.js.
Output
This will produce the following output −
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