TGW
TGW

Reputation: 835

Regex to check space after individual single quote or individual double quote

I have to check for individual single or double quotes using regex if there are no alphabets or numbers in string.

For example:

Max's --> is valid
' --> Invalid
" --> Invalid 

So I used a regex

^(?=.*[\\w\\d]).+

This works pretty much fine except it also allows

Max" M--> Here there is space after quote which is supposed to be invalid
While Max"M M --> should be valid same goes for single quote 

What changes should I do to achieve that condition for validation ?

Example :

There should be at least one alphabet or a numeric character, only special characters are not allowed. If input string is:

' --> Is invalid
" --> Is invalid
# --> Is invalid
^ --> Is invalid
and so on...

but if the input string is

Max's pc --> Valid
1's --> Valid
Max"s pc --> Valid
1"s --> Valid

but again if it is

Max' --> Invalid as the word ends with '
Max" --> Invalid as the word ends with "

Here I do not want my word to end with ' or " or any other special character but yes commas, semicolons or full stops are allowed.

Please mention if any further clarification is required. Thanks :)

Upvotes: 0

Views: 187

Answers (2)

suresh kumar
suresh kumar

Reputation: 167

try this regex according to your requirement. [a-zA-Z0-9]['"][\S]

var regex = /[a-zA-Z0-9]['"][\S]/;

function getValue()  {
    return document.getElementById("myinput").value;
}

function test() {
    alert(regex.test(getValue()));
}

https://jsfiddle.net/uf8z1eh3/

Upvotes: 1

kip
kip

Reputation: 1140

I'm not sure but this maybe can work:

var text = [
    "'",
    '"',
    '#',
    '^',
    "Max's pc",
    "1's",
    'Max"s pc',
    '1"s',
    "Max'",
    'Max"',
    'Max" M'
];

var expr = /([^\s\w\d]+)(?=[\w\d]+)/;

text.map(function(v) {
   console.log(v, expr.test(v)); 
});

EDIT

Added more examples

var text = [
    "Max's",
    'Max"s',
    "Max' s",
    'Max" s',
];

var expr = /([^\s\w\d]+)(?=[\w\d]+)/;

text.map(function(v) {
   console.log(v, expr.test(v)); 
});

Upvotes: 1

Related Questions