简体   繁体   English

Javascript正则表达式取代“拆分”

[英]Javascript regex to replace “split”

I would like to use Javascript Regex instead of split . 我想使用Javascript Regex而不是split

Here is the example string: 这是示例字符串:

var str = "123:foo";

The current method calls: 当前方法调用:

str.split(":")[1]

This will return "foo" , but it raises an Error when given a bad string that doesn't have a : . 这将返回"foo" ,但是在给出不带:的错误字符串时会引发错误。

So this would raise an error: 因此,这将引发错误:

var str = "fooblah";

In the case of "fooblah" I'd like to just return an empty string . 对于"fooblah"我只想返回一个空字符串

This should be pretty simple, but went looking for it, and couldn't figure it out. 这应该很简单,但是一直在寻找它,却无法弄清楚。 Thank you in advance. 先感谢您。

Remove the part up to and including the colon (or the end of the string, if there's no colon): 删除直到并包括冒号(或字符串的末尾,如果没有冒号)的部分:

"123:foo".replace(/.*?(:|$)/, '')    // "foo"
"foobar" .replace(/.*?(:|$)/, '')    // ""

How this regexp works: 此正则表达式如何工作:

.*                 Grab everything
?                  non-greedily
(                  until we come to
  :                a colon
  |                or 
  $                the end of the string
)

A regex won't help you. 正则表达式不会帮助您。 Your error likely arises from trying to use undefined later. 您的错误可能是由于稍后尝试使用undefined引起的。 Instead, check the length of the split first. 相反,请先检查拆分的长度。

var arr = str.split(':');
if (arr.length < 2) {
  // Do something to handle a bad string
} else {
  var match = arr[1];
  ...
}

Here's what I've always used, with different variations; 这是我一直使用的,有不同的变化; this is just a simple version of it: 这只是它的一个简单版本:

function split(str, d) {
    var op = "";
    if(str.indexOf(d) > 0) {
        op = str.split(d);
    }
    return(op);
}

Fairly simple, either returns an array or an empty string. 非常简单,要么返回一个数组,要么返回一个空字符串。

 var str1 = "123:foo", str2 = "fooblah"; var res = function (s) { return /:/.test(s) && s.replace(/.*(?=:):/, "") || "" }; console.log(res(str1), res(str2)) 

这是使用单个正则表达式的解决方案,您需要将其包含在捕获组中:

^[^:]*:([^:]+)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM