How to remove everything but letters, numbers, space, exclamation and question mark from string?

前端 未结 4 593
礼貌的吻别
礼貌的吻别 2021-02-07 01:08

How to remove everything but:

letters, numbers, spaces, exclamation marks, question marks from a string?

It\'s important that the method supports international l

4条回答
  •  青春惊慌失措
    2021-02-07 01:37

    text = "A(B){C};:a.b*!c??!1<>2@#3"
    result = text.replace(/[^a-zA-Z0-9]/g, '')
    

    Should return ABCabc123

    First, we define text as A B C a b c 1 2 3 but with random characters set the result as:

    text.replace(...) where the parameters are:

    /.../g, /.../: ^ means to reverse; not to remove the letters which are:

    a-z(lowercase letters), A-Z(UPPERCASE letters) and 0-9(digits)

    g means global, to remove all matches not just the first match

    The second parameter is the replacement character, we set it to an empty string so that it just keeps the specified string. if is specified, it will return this: "A B C a b c 1 2 3"

提交回复
热议问题