javascript在逗号后截断字符串 [英] javascript Truncate string after comma

查看:99
本文介绍了javascript在逗号后截断字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来删除逗号和字符串后面的所有内容,例如:

I'm looking for a way to remove the comma and all that comes after it in a string, for example:


重要,不那么重要

important, not so important

我想删除,不那么重要

有什么想法吗?提前致谢!

Any ideas? Thanks in advance!

推荐答案

你可以用 substring indexOf

You can do it with substring and indexOf:

str = str.substring(0, str.indexOf(','));

但你必须确保逗号在那里(之前测试过)。

but you'd have to be sure that a comma is in there (test it before).

另一种可能性是使用 split()

Another possibility is to use split():

str = str.split(',')[0];

即使没有事先测试也能正常工作,但可能会执行不必​​要的字符串操作(在小字符串上可能忽略不计) 。

this works even without testing beforehand but might perform unnecessary string operations (which is probably negligible on small strings).

这篇关于javascript在逗号后截断字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆