开发者

regular expression to remove substring and all characters after x

开发者 https://www.devze.com 2023-03-30 20:12 出处:网络
I\'m having problems with a regular expression. I have a string like this: /Date(-62135596800000+0100)/

I'm having problems with a regular expression. I have a string like this:

/Date(-62135596800000+0100)/

I would like to remove everything up until and including the opening parenthesis and everything after the + sign, so far I've come up with this:

 [\/D开发者_C百科ate(]|\+(.*)

Which has two issues, 1) it is matching the single characters /, D, a etc. instead of matching the substring '/Date(' and 2) it throws and error when using replace like so:

function returnNewString(oldString) {
    var re = [\/Date(]|+(.*),
    output = oldString.replace(re,'');
    return output;
}

I'm rather new to reg-ex so the above might be wrong in every way possible so any help would be apreciated, thanks


Assuming your text will always look like that, you can use this:

function returnNewString(oldString) {
    return oldString.match(/[-\d]+/);
}

If, on the other hand, you might have a string like /Date(+62135596800000+0100)/ or like /Date(62135596800000+0100)/, then you should use this:

function returnNewString(oldString) {
    return oldString.match(/(?:-|\+)?\d+/);
}


'/Date(-62135596800000+0100)/'.replace(/\/Date\((.*?)\+.*\)\//, '$1');

Explanation: The unescaped parentheses match the part between the opening parenthesis in your string and the plus sign, which is the only thing ($1) the whole string is replaced with.


/Date((-?\d+)+\d+)/ Group 1 will contain the desired portion of your string.

For example, if your input is "/Date(-62135596800000+0100)/" then

Group 0 (entire match) will be "/Date(-62135596800000+0100)/" and
Group 1 will be -62135596800000

0

精彩评论

暂无评论...
验证码 换一张
取 消