Javascript regular expression: match anything up until something (if there it exists)

后端 未结 5 1758
盖世英雄少女心
盖世英雄少女心 2021-02-05 06:18

Hi I am new to regular expression and this may be a very easy question (hopefully).

I am trying to use one solution for 3 kind of string

  • \"45%\", expected
5条回答
  •  一个人的身影
    2021-02-05 06:28

    to match 45, 45%, and any number of any length use this (182%, 18242, etc)

    str.match(/([0-9]+)([%]?)/)[1];
    

    if you need to match the empty string also include it as ^$, note match("...")[1] will be undefined for the empty string, so you will need to test for match and then check [0] or see if [1] is undefined.

    str.match(/([0-9]+)([%]?)|^$/)
    

    if you need to match exactly two digits use {2,2} anchor the expression between begin and end line characters: "^(exp)$"

    str.match(/^([0-9]{2,2})([%]?)$/)[1];
    

提交回复
热议问题