修剪javascript?这段代码在做什么? [英] trim in javascript ? what this code is doing?

查看:134
本文介绍了修剪javascript?这段代码在做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中寻找一个不存在的修剪函数,Googling上的一些代码建议使用:

I was looking for a trim function in JavaScript which doesn't exist and some code on Googling suggests that use:

function trimStr(str) {
  return str.replace(/^\s+|\s+$/g, '');
}

我想知道 str.replace(/ ^ \s + | \s + $ / g,'')
有效。我知道这是正则表达的某种形式,但不知道它在做什么。

I want to know how str.replace(/^\s+|\s+$/g, '') works. I understand that this is some form of regular expression but dont know what it is doing.

推荐答案

/ ^ \s + | \s + $ / g 从字符串的开头或结尾搜索空格。表达式可以分为两部分, ^ \s + \s + $ ,由<$分隔c $ c> | (或)。第一部分从字符串的开头( ^ )开始,并包含尽可能多的空白字符( \s + )。第二部分使用相反的方式,但最后使用美元符号( $ )。

/^\s+|\s+$/g searches for whitespace from either the beginning or the end of the string. The expression can be split into two parts, ^\s+ and \s+$ which are separated by | (OR). The first part starts from the beginning of the string (^) and includes as many whitespace characters it can (\s+). The second part does the same but in reverse and for the end using the dollar sign ($).

In简单的英语,正则表达式将是这样的:

In plain english, the regular expression would go like this:


从字符串的开头尽可能多的空格字符或尽可能多的空格最后的字符。

Find as many whitespace characters from the beginning of the string as possible or as many whitespace characters from the end as possible.

请注意 \s 匹配空格,标签和换行符。

Note that \s matches spaces, tabs and line breaks.

最后的 / g 部分启用全局搜索,允许多次替换(例如,不仅仅是开头,而是字符串的结尾)。

The /g part at the end enables global searching, which allows multiple replacements (eg. not just the beginning, but the end of the string also).

这篇关于修剪javascript?这段代码在做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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