[英]How can i remove all characters started with # from a textarea using jquery or javascript?
I have the code below 我有下面的代码
<textarea id="description" name="description" rows="10" placeholder="Description..." class="valid">
This is an example text i wanna keep.
# And i want to remove all this content.
</textarea>
how can i remove only this text from the textarea 我怎样才能从textarea中删除此文本
# And i want to remove all this content.
using jquery or javascript ? 使用jquery或javascript?
As you can see i want all the content that start with a hashtag to be removed. 正如您所看到的,我希望删除以#标签开头的所有内容。
Only for textarea, you may use a simple Regular Expression, with "m" (multiline) flag. 仅对于textarea,您可以使用带有“m”(多行)标志的简单正则表达式。
• Where $
means end of the line; •
$
表示行尾;
• special .
•特别
.
matches with any symbol, 与任何符号匹配,
• *
means 'match from zero to infinite times' •
*
表示'从零到无限次匹配'
let desc = document.getElementById('description'); desc.value = desc.value.replace(/#.*$/gm,"");
textarea {width: 80%;}
<textarea class="js-replace" id="description" name="description" rows="10" placeholder="Description..."> This is an example text i wanna keep. # And i want to remove all this content. Bubu and replace #Me But not me! </textarea>
Version for multiple elements, textarea, div, etc - replace by className: 多个元素的版本,textarea,div等 - 由className替换:
let replace = document.querySelectorAll('.js-replace') for( let i = 0; i < replace.length; i++ ){ let area = /TEXTAREA|INPUT/.test(replace[i].tagName); // will return true or false; let content = area ? "value" : "innerHTML"; // Ternary operator. (condition) ? (value if true) : (value otherwise) // replace[i]['value'] if textarea and replace[i]['innerHTML'] if other element replace[i][content] = replace[i][content].replace(/#.*?(\\n|<br>|$)/g, "$1"); // (*1) }
textarea {width: 80%;}
<textarea class="js-replace" id="description" name="description" rows="10" placeholder="Description..."> This is an example text i wanna keep. # And i want to remove all this content. Bubu and replace #Me But not me! </textarea> <div class="js-replace"> This is an example text i wanna keep. <br># And i want to remove all this content. <br> <br>Bubu and replace #Me <br>But not me! </div>
(*1): .replace(/#.*?(\\n|<br>)/g, "$1")
— string, starting from #
symbol, matching .*
anything (instead of line-break \\n
), many times, and ?
(* 1)
.replace(/#.*?(\\n|<br>)/g, "$1")
- 字符串,从#
符号开始,匹配.*
any(而不是line-break \\n
),很多次,和?
stop as soon as it faces with \\n
line break |
一旦停止,因为它与面临
\\n
换行符|
or <br>
HTML-line break. 或
<br>
HTML的换行符。 "$1"
— equals to match in the first (parentheses). "$1"
- 等于第一个(括号)匹配。 Ie we replace all string, but keep line-break. 即我们替换所有字符串,但保持换行符。
But this will not work correctly, if you want to delete, for example, comments from Python... because you may delete strings with "str... # str"
但是如果要删除Python中的注释,这将无法正常工作...因为您可能会删除带有
"str... # str"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.