Javascript - 查找字符串中存在的逗号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6871532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:33:58  来源:igfitidea点击:

Javascript - Find Comma Exists In String

javascript

提问by logic-unit

I need to find if a comma exists in a javascript string so I know whether to do str.split(',') on it or not.

我需要查找javascript字符串中是否存在逗号,以便我知道是否对其执行 str.split(',') 。

Is this the correct way: var myVar = str.search(',');?

这是正确的方法:var myVar = str.search(',');

If the value of myVar is greater than 0 (zero) then there is a comma in the string?

如果 myVar 的值大于 0(零),那么字符串中是否有逗号?

I'm just not sure if I've got the parameter right in search()

我只是不确定我是否在 search() 中得到了正确的参数

Thanks!

谢谢!

回答by ChristopheCVB

Try using indexOffunction:

尝试使用indexOf功能:

if (string.indexOf(',') > -1) { string.split(',') }

回答by Aron Rotteveel

.search()is used for regular expressions, making it a bit overkill for this situation.

.search()用于正则表达式,在这种情况下有点矫枉过正。

Instead, you can simply use indexOf():

相反,您可以简单地使用indexOf()

if (str.indexOf(',') != -1) {
    var segments = str.split(',');
}

.indexOf()returns the position of the first occurrenceof the specified string, or -1if the string is not found.

.indexOf()返回指定字符串第一次出现的位置,或者-1如果未找到该字符串。

回答by danigonlinea

Use new functions natively coming from ES6:

使用原生来自 ES6 的新函数:

const text = "Hello, my friend!";
const areThereAnyCommas = text.includes(',');

回答by Talha Ahmed Khan

var strs;
if( str.indexOf(',') != -1 ){
    strs = str.split(',');
}