简体   繁体   中英

Javascript regex to replace “split”

I would like to use Javascript Regex instead of 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 : .

So this would raise an error:

var str = "fooblah";

In the case of "fooblah" I'd like to just return an empty string .

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. 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)) 

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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