简体   繁体   English

Javascript正则表达式,用于删除文本

[英]Javascript Regular Expression for removing text

I want to replace a string of characters in an html tag using JavaScript. 我想使用JavaScript替换html标记中的字符串。 So in this example I want to remove everything between the <table and <tbody> . 因此,在此示例中,我想删除<table<tbody>之间的所有内容。 I'm using the replace function and a regular expression. 我正在使用replace函数和一个正则表达式。 The regular expression construction must be wrong somewhere. 正则表达式构造在某处一定是错误的。 Here is what I currently have: 这是我目前拥有的:

str = str.replace(/([<table]\w*\W*[<tbody>])/, "");

The regular expression logic as I see it is like this (correct me where I'm wrong): 我所看到的正则表达式逻辑是这样的(在错误的地方纠正我):

  1. I'm looking for the string match of <table so I put that string in the brackets as I want that to match exactly as written. 我正在寻找<table的字符串匹配项,因此我将该字符串放在方括号中,因为我希望它与编写的字符串完全匹配。

  2. Then I place a \\w*\\W* because I expect 1 or more of both alphanumeric and non alphanumeric characters to follow. 然后,我放置一个\\ w * \\ W *,因为我希望后面跟随一个或多个字母数字和非字母数字字符。

  3. Finally I place the "< tbody>" in the brackets because I expect that format exactly. 最后,我将“ <tbody>”放在方括号中,因为我希望该格式完全正确。

So the results are not as I expected. 因此结果与我预期的不同。 There is no other <tbody> or <table in my string so I don't know what I'm doing wrong. 我的字符串中没有其他<tbody><table ,所以我不知道自己在做什么错。

This is what the string looks like before I replace the characters with nothing. 这就是在我什么都没有替换字符之前,字符串的样子。

"\n\t\t\t\t\t\t\n                                                <div>\n\t\t\t\t\t\t\t
<table id=\"gvStation_ctl19_gvExtRows\" style=\"border-collapse: collapse;\" border=\"1\" rules=\"all\" cellspacing=\"0\">
\n\t\t\t\t\t\t\t\t<tbody>
  1. The brackets find any character between in any order so you don't need it in this case. 方括号以任何顺序找到它们之间的任何字符,因此在这种情况下您不需要它。 See http://www.w3schools.com/jsref/jsref_obj_regexp.asp . 参见http://www.w3schools.com/jsref/jsref_obj_regexp.asp
  2. \\w* and \\W* don't match the whitespaces. \\w*\\W*不匹配空格。

Here is the solution : /<\\s*table(?:.|\\s)*<\\s*tbody\\s*>/i 这是解决方案:/< /<\\s*table(?:.|\\s)*<\\s*tbody\\s*>/i :.| /<\\s*table(?:.|\\s)*<\\s*tbody\\s*>/i

 var str = '"\\n\\t\\t\\t\\t\\t\\t\\n < div>\\n\\t\\t\\t\\t\\t\\t\\t < table id=\\"gvStation_ctl19_gvExtRows\\" style=\\"border-collapse: collapse;\\" border=\\"1\\" rules=\\"all\\" cellspacing=\\"0\\"> \\n\\t\\t\\t\\t\\t\\t\\t\\t< tbody>'; str = str.replace(/<\\s*table(?:.|\\s)*<\\s*tbody\\s*>/i, ""); alert(str); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM