如何使用 typescript 确保我的字符串中有两个单词。
我需要这个的原因是只有当名称采用“名字”格式时我才会调用服务器。
最佳答案
答案确实不依赖于 TypeScript。这是基本的 JavaScript。
您可以使用正则表达式perform a test 在字符串上:
function testString(input){
// Return whether or not there are letters (any amount and any case)
// followed by one space and then more letters (any amount and any case).
// Of course, if you wanted to get more specific about case or character
// counts, adjusting the regular expression would be simple.
return /^[A-Za-z]+ [A-Za-z]+$/.test(input);
}
console.log(testString("Scott"));
console.log(testString("Scott Marcus"));
console.log(testString("Scott\nMarcus"));
关于javascript - 如何确保我的字符串在 typescript 中有两个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46372464/