Javascript分割功能在新行或空白处拆分成数组 [英] Javascript split function to split into array at new line or white space

查看:88
本文介绍了Javascript分割功能在新行或空白处拆分成数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过空格和/或新行拆分一些文本,并在整个文本之前和之后删除空格,以防万一。我不知道如何执行此操作,因为我无法理解正则表达式(我已尝试过其他人的正则表达式,但它会破坏我的输出)并且我想使用最佳实践执行此操作而不是编写一些冗长的错误解决方法

I'm trying to split some text either by whitespace and/or new line, and also remove the white space before and after the whole text, just in case. I'm not sure how to perform this as I cannot get my head around regex (I've tried other people's regex but it breaks my output) and I want to perform this using best practice rather than writing some lengthy buggy workaround

我的代码可以在这里找到: https:// github.com/Dave-Melia/Text-Separator

My code can be located here: https://github.com/Dave-Melia/Text-Separator

非常感谢

D

推荐答案

要拆分任何空格(包括换行符),你可以使用 / \s / with split

To split on any whitespace (including newlines), you'd use /\s/ with split:

var theArray = theString.split(/\s+/);

\s 表示空格(例如,whitespace —包括换行符), + 表示一个或更多

\s means "spaces" (e.g., whitespace — including newlines), and + means "one or more".

要首先从字符串的开头和结尾修剪空格,在任何现代浏览器上都可以使用字符串#trim

To trim whitespace from the beginning and end of the string first, on any modern browser you can use String#trim:

var theArray = theString.trim().split(/\s+/);

如果你必须支持旧浏览器,你可以使用替换

If you have to support older browsers, you can use replace:

var theArray = theString.replace(/^\s+|\s+$/g, '').split(/\s+/);

替换一起使用的正则表达式可以使用一点解释: http://regex101.com/r/sS0zV3/1

That regex used with replace can use a bit of explanation: http://regex101.com/r/sS0zV3/1


  • ^ \s + 表示字符串开头的任何空格

  • | 表示或(如那个)(称为交替)

  • \s + $ 表示字符串末尾的任何whitepsace

  • ^\s+ means "any whitespace at the beginning of the string
  • | means "or" (as in , "this or that") (it's called an "alternation")
  • \s+$ means "any whitepsace at the end of the string

然后我们用''替换所有出现的事件( g )(一个空白)字符串)。

Then we replace all occurrences (g) with '' (a blank string).

这篇关于Javascript分割功能在新行或空白处拆分成数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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