How to remove all characters from a string

后端 未结 3 947
北荒
北荒 2020-12-16 02:15

How can I remove all characters from a string that are not letters using a JavaScript RegEx?

3条回答
  •  猫巷女王i
    2020-12-16 02:44

    RegEx instance properties used g , i

    global : Whether to test the regular expression against all possible matches in a string, or only against the first.

    ignoreCase : Whether to ignore case while attempting a match in a string.

    RegEx special characters used [a-z] , +

    [^xyz] : A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets. You can specify a range of characters by using a hyphen.

    For example, [abcd] is the same as [a-d]. They match the 'b' in "brisket" and the 'c' in "chop".

    + : Matches the preceding item 1 or more times. Equivalent to {1,}.

    JavaScript string replace method syntax

    str.replace(regexp|substr, newSubStr|function[, Non-standard flags]);

    The non-standard flags g & i can be passed in the replace syntax or built into the regex. examples:

    var re = /[^a-z]+/gi;   var str = "this is a string";   var newstr = str.replace(re, "");   print(newstr);
    
    var str = "this is a string";   var newstr = str.replace(/[^a-z]+/, "", "gi");   print(newstr);
    

    To match whitespace characters as well \s would be added to the regex [^a-z\s]+.

    JavaScript Reference

提交回复
热议问题