我需要查找javascript字符串中是否存在逗号,以便我知道是否对它执行str.split(',').
这是正确的方法:var myVar = str.search(',');?
如果myVar的值大于0(零),那么字符串中有逗号?
我只是不确定我是否在搜索()中获得了正确的参数
谢谢!
Chr*_*CVB 53
尝试使用indexOf功能:
if (string.indexOf(',') > -1) { string.split(',') }
Run Code Online (Sandbox Code Playgroud)
dan*_*nea 10
使用原生来自 ES6 的新函数:
const text = "Hello, my friend!";
const areThereAnyCommas = text.includes(',');
Run Code Online (Sandbox Code Playgroud)
.search() 用于正则表达式,在这种情况下有点矫枉过正。
相反,您可以简单地使用indexOf():
if (str.indexOf(',') != -1) {
var segments = str.split(',');
}
Run Code Online (Sandbox Code Playgroud)
.indexOf()返回指定字符串第一次出现的位置,或者-1如果未找到该字符串。
| 归档时间: |
|
| 查看次数: |
52609 次 |
| 最近记录: |