Regex for开发者_运维技巧 not allowing single quotes and double quotes in javascript
.
A simple regex (although, maybe this is not the best approach to use regex here):
var onlyValidCharacters = /^[^'"]*$/.test(myString);
Non-regex solution (probably faster in simple cases):
if (myString.indexOf("\"") != -1 || myString.indexOf("'") != -1)
alert("invalid characters");
If the goal is to print a string that contains single and double quotes while maintaining the quotes in the string, use these ``. Concretely, you can do the following:
console.log(`The word for the fear of long words is "hippopotomonstrosesquipedaliophobia." That's sick!`);
Also, JavaScript matches its opening quotation marks with the closing quotation marks and ignores other quotation marks within the string, thus eliminating the need for escape character on the marks. i.e
console.log("That's totally fine");
console.log('Did you just say "Gooth"?');
精彩评论