Js Using regular expressions to remove brackets from strings
- 2021-09-24 21:21:30
- OfStack
let str = ' This is 1 String [html] Statement ;[html] Strings are common ';
alert(str.replace(/\[|]/g,''));// Removes all of the [] Brackets (excluding their contents)
// Output: This is 1 String html Statement ;html Strings are common
alert(str.replace(/\[.*?\]/g,''));// Removes all of the [] Brackets (including their contents)
// Output: This is 1 String statements ; Strings are common
Remove all brackets, excluding their contents
let str = "[1,2,3,4,5,6,7,8]";
let newStr = str.replace(/\[|]/g,'');
console.log(newStr);//1,2,3,4,5,6,7,8
Remove all brackets, including their contents
let str = "[1,2,3,4,5,6,7,8]";
let newStr = str.replace(/\[.*?\]/g,'');
console.log(newStr);//''
Symbolic Interpretation of Regular Expressions
"": Marks the next 1 character as a special character, or as a literal character, or as a backward reference, or as an octal escape character. For example, "n" matches the character "n". "\ n" matches a newline character. Serial "\" matches "\" and "(" matches "(");
": the meaning of or;
"/g": Global search. Because all brackets in the string should be removed here, the global search should be turned on in the regular;
".": Represents any character other than line feeds and other Unicode line terminators;
'*': Matches the preceding subexpression zero or more times. For example, zo can match "z" and "zoo". Equivalent to {0,};
"?" Matches the preceding subexpression zero times or once. For example, "do (es)?" You can match "do" in "does" or "does". ? Equivalent to {0, 1}. (Greedy model)
PS: Here are two very convenient regular expression tools for your reference:
JavaScript Regular Expression Online Test Tool:
http://tools.ofstack.com/regex/javascript
Regular expression online generation tool:
http://tools.ofstack.com/regex/create_reg
Summarize
Of course, there are many ways to solve it, and regularity is the clearest and clearest way.