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
# And i want to remove all this content.
using jquery or 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.
• 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:
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 ?
stop as soon as it faces with \\n
line break |
or <br>
HTML-line break. "$1"
— equals to match in the first (parentheses). 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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.