user544079
user544079

Reputation: 16629

Check if string is enclosed in single quotes Javascript

// 'Apple' : valid
// 'Apple : Invalid
// Apple : Invalid

if(str.indexOf('\'') > -1 && str.indexOf('"') > -1){
   // do something
}

This will detect if the string contains single and double quotes.

How to check if string starts and ends with a single quote. (Regexp)?

Upvotes: 8

Views: 12973

Answers (5)

fakie
fakie

Reputation: 720

ES6

if (str.startsWith("'") && str.endsWith("'")) {
  // do something
}

Not supported in IE

MDN startsWith endsWith

Upvotes: 1

Cory Arnold
Cory Arnold

Reputation: 1

if((name[0] == "'" && name[name.length - 1] == "'")||(name[0] == '"' && name[name.length - 1] == '"')){
    ///
}

I'd suggest this... It's a total plagiarism of Daniel Robinson's answer, just more complete.

Upvotes: 0

Daniel Robinson
Daniel Robinson

Reputation: 3387

if(str[0] == "'" && str[str.length - 1] == "'"){
   // do something
}

Upvotes: 14

Scimonster
Scimonster

Reputation: 33409

/^'.*'$/.test(str)

Regex for starts and ends with a single quote.

Upvotes: 3

James Thorpe
James Thorpe

Reputation: 32202

No need for regex, you can use the charAt function:

if (str.charAt(0) == "'" && str.charAt(str.length-1) == "'") {

}

Upvotes: 1

Related Questions