Regex remove all special characters except numbers?

前端 未结 5 1915
滥情空心
滥情空心 2021-01-31 09:09

I would like to remove all special characters (except for numbers) from a string. I have been able to get this far

var name = name.replace(/[^a-zA-Z ]/, \"\");
<         


        
相关标签:
5条回答
  • 2021-01-31 09:13

    to remove symbol use tag [ ]

    step:1

    []
    

    step 2:place what symbol u want to remove eg:@ like [@]

    [@]
    

    step 3:

    var name = name.replace(/[@]/g, "");
    

    thats it

    var name="ggggggg@fffff"
    var result = name.replace(/[@]/g, "");
    console .log(result)

    Extra Tips

    To remove space (give one space into square bracket like []=>[ ])

    [@ ]
    

    It Remove Everything (using except)

    [^place u dont want to remove]
    

    eg:i remove everyting except alphabet (small and caps)

    [^a-zA-Z ]
    

    var name="ggggg33333@#$%^&**I(((**gg@fffff"
    var result = name.replace(/[^a-zA-Z]/g, "");
    console .log(result)

    0 讨论(0)
  • 2021-01-31 09:22

    This should work as well

    text = 'the car? was big and* red!'

    newtext = re.sub( '[^a-z0-9]', ' ', text)

    print(newtext)

    the car was big and red

    0 讨论(0)
  • 2021-01-31 09:24

    If you don't mind including the underscore as an allowed character, you could try simply:

    result = subject.replace(/\W+/g, "");
    

    If the underscore must be excluded also, then

    result = subject.replace(/[^A-Z0-9]+/ig, "");
    

    (Note the case insensitive flag)

    0 讨论(0)
  • 2021-01-31 09:33

    To remove the special characters, try

    var name = name.replace(/[!@#$%^&*]/g, "");
    
    0 讨论(0)
  • 2021-01-31 09:34

    Use the global flag:

    var name = name.replace(/[^a-zA-Z ]/g, "");
                                        ^
    

    If you don't want to remove numbers, add it to the class:

    var name = name.replace(/[^a-zA-Z0-9 ]/g, "");
    
    0 讨论(0)
提交回复
热议问题