I'm trying to take text that users input into a textarea and check it against a custom dictionary file. As a first step, I'd like to parse the input and strip out non-alphanumeric characters (which would likely contain punctuation) and extra spaces / newline characters and end up with a string of words separated by single spaces.
For example, start with
The child said,
"Bye"!
and end up with
The child said Bye
I tried the following, but whenever there is a new line, it is replacing the newline character with a literal "n" in the comment_stripped
variable. How can I get it to return comment_stripped
as words separated by spaces without adding "n" characters?
jQuery(document).ready(function($){
var comment_raw = '';
var comment_stripped = '';
$("#comment").on("input", function(){
comment_raw = ($(this).val());
comment_stripped = JSON.stringify(comment_raw).replace(/[^\w\s]|_/g, "").replace(/\n/g, " ").replace(/\s+/g, " ");
console.log('comment raw = '+comment_raw);
console.log('comment stripped = '+comment_stripped);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="comment" name="comment" cols="45" rows="8" maxlength="65525" required="required" autocomplete="off" autocorrect="off" autocapitalize="none" spellcheck="false"></textarea>
JSON.stringify
on a string? – Chris G