博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何判断一个字符串在JavaScript中是否包含某个字符?
阅读量:2291 次
发布时间:2019-05-09

本文共 1819 字,大约阅读时间需要 6 分钟。

本文翻译自:

I have a page with a textbox where a user is supposed to enter a 24 character (letters and numbers, case insensitive) registration code. 我有一个带有文本框的页面,用户应在其中输入24个字符(字母和数字,不区分大小写)的注册码。 I used maxlength to limit the user to entering 24 characters. 我使用maxlength将用户限制为输入24个字符。

The registration codes are typically given as groups of characters separated by dashes, but I would like for the user to enter the codes without the dashes. 注册代码通常以破折号分隔的字符组形式给出,但是我希望用户输入不带破折号的代码。

How can I write my JavaScript code without jQuery to check that a given string that the user inputs does not contain dashes, or better yet, only contains alphanumeric characters? 如何在没有jQuery的情况下编写我的JavaScript代码,以检查用户输入的给定字符串不包含破折号,或者更好的是,仅包含字母数字字符?


#1楼

参考:


#2楼

检查字符串(单词/句子...)是否包含特定的单词/字符

if ( "write something here".indexOf("write som") > -1 )  { alert( "found it" );  }

#3楼

Working perfectly.This exmple will help alot. 完美的工作。这个例子会很有帮助。

    

My form

UserName :

Password :


#4楼

Try this: 尝试这个:

if ('Hello, World!'.indexOf('orl') !== -1)    alert("The string 'Hello World' contains the substring 'orl'!");else    alert("The string 'Hello World' does not contain the substring 'orl'!");

Here is an example: 这是一个示例: :


#5楼

You're all thinking too hard. 你们都在想 Just use a simple Regular Expression, it's your best friend. 只需使用一个简单的正则表达式,它就是您最好的朋友。

var string1 = "Hi Stack Overflow. I like to eat pizza."var string2 = "Damn, I fail."var regex = /(pizza)/g // Insert whatever phrase or character you want to findstring1.test(regex); // => truestring2.test(regex); // => false


#6楼

var inputString = "this is home"; var findme = "home"; if ( inputString.indexOf(findme) > -1 ) { alert( "found it" ); } else { alert( "not found" ); }

转载地址:http://mgcnb.baihongyu.com/

你可能感兴趣的文章
面试官:聊聊 Spring 中的线程安全性
查看>>
一篇文教你在 Java 中利用 redis 实现分布式全局唯一标识服务
查看>>
深入浅出数据库事务和4种隔离级别
查看>>
对限频限流的思考
查看>>
面试屡屡碰壁,痛定思痛闭关修炼!半年后4面阿里成功拿offer
查看>>
服!看完阿里大牛手写的Java异步编程实战笔记,我惊呆了
查看>>
Java程序员跳槽,三面之后被拒,原因竟是“招不起”
查看>>
想要彻底搞懂微服务架构?必先学:SpringBoot+SpringCloud+docker
查看>>
6天面试10家,已经拿到offer,Java程序员的面试总结分享
查看>>
渣本的逆袭之路!备战3个月,三面蚂蚁金服成功斩获Offer
查看>>
10月末美团、滴滴、蘑菇街9次面试总结(Java岗)
查看>>
热气腾腾的腾讯后台开发面经(总共五面)
查看>>
深入理解设计模式(设计原则+种设计模式+设计模式PK+设计模式混编)
查看>>
谷歌大佬回国发展,吊打各大厂面试官!吐血总结大厂面试高频点及笔记解析
查看>>
面试复盘:面完字节、美团、阿里等大厂,今年面试到底问什么?
查看>>
从0到1,决战Spring Boot《Spring Boot 2实战之旅》
查看>>
5面终于拿到字节跳动offer!忍不住和大家分享一波
查看>>
拿到阿里、字节offer后。我总结了一线大厂Java面试重难点:Java基础+并发+JVM+算法+框架+分布式+架构设计
查看>>
金九银十已过 成功入职美团,面试回顾及个人总结:算法+框架+Redis+分布式+JVM
查看>>
香!阿里P8手写3份满级“并发编程”笔记,原理→精通→实战
查看>>