0

I have below strings -

var string1 = "When did Harry meet Sally ???";
var string2 = "When did Harry meet Sally ?$@";
var string3 = "When did Harry meet Sally ?";

I need to report string3 as correct string out of the above options. With

string1.match(/[:!?+\<">'$‘;@€`*&.\\/]{2}/g) 

I am able to say string1 is incorrect. How can detect that string2 is incorrect ?

4
  • What about "What a beautiful day!!!" Commented Apr 11, 2017 at 9:00
  • so a valid string should contain less than 3 consecutive puctuations? Commented Apr 11, 2017 at 9:01
  • valid string should contain only one punctuation. It is fine if there are multiple punctuation but they should not be in series together. Commented Apr 11, 2017 at 9:08
  • "What a beautiful day!!!" should show as incorrect "What a beautiful day!" should be the correct one. Commented Apr 11, 2017 at 9:08

2 Answers 2

1

You can use positive lookahead to check if current character is a symbol and character following it is also symbol then return false.

Edit1

To handle cases like ? @, you can remove all spaces and then test it. This will not modify original string, and is only used for validation purpose.

Sample

function validateString(str){
  return !/[^a-z0-9](?=[^a-z0-9])/gi.test(str.replace(/\s+/g, ''))
}


var string1 = "When did Harry meet Sally ???";
var string2 = "When did Harry meet Sally ?$@";
var string3 = "When did Harry meet Sally ?";
var string4 = "When did Harry meet Sally ? @";
var string5 = "When did Harry meet Sally ? test";

[string1, string2, string3, string4, string5].forEach(function(s){
  console.log(validateString(s))
})

Sign up to request clarification or add additional context in comments.

1 Comment

What if we have to show var string4 = "When did Harry meet Sally ? @" ; as incorrect ?
1

Push these sting to an array , so that i , they can can be looped, The regex will return the last two characters.

var string1 = "When did Harry meet Sally ???";
var string2 = "When did Harry meet Sally ?$@";
var string3 = "When did Harry meet Sally ?";

var stringArray = [string1,string2,string3]

stringArray.forEach(function(item){
// will get last two characters else null
 var x = item.match(/[:!?+\<">'$‘;@€`*&.\\/]{2}/g);
 // if null then log the string
 x=== null?console.log(item):''
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.