Я пытаюсь взять текст, который пользователи вводят в текстовое поле, и сравнить его с файлом пользовательского словаря. В качестве первого шага я хотел бы проанализировать ввод и удалить не буквенно-цифровые символы (которые, вероятно, будут содержать знаки препинания) и лишние пробелы/символы новой строки, и в итоге получить строку слов, разделенных одиночными пробелами.
Например, начните с
The child said,
"Bye"!
И в конечном итоге с
The child said Bye
Я пробовал следующее, но всякий раз, когда появляется новая строка, она заменяет символ новой строки буквой «n» в переменной comment_stripped. Как я могу заставить его возвращать comment_stripped в виде слов, разделенных пробелами, без добавления символов «n»?
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.info('comment raw = '+comment_raw);
console.info('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>
@ChrisG о, я видел это в каком-то примере. возможно, это не нужно
Это единственная вещь, которая ломает ваш код :) Он превращает объекты в текст JSON.
JSON.stringify не требуется. Попробуй это
jQuery(document).ready(function($) {
var comment_raw = '';
var comment_stripped = '';
$("#comment").on("input", function() {
comment_raw = ($(this).val());
comment_stripped = comment_raw.replace(/[^\w\s]|_/g, "").replace(/\n/g, " ").replace(/\s+/g, " ");
console.info('comment raw = ' + comment_raw);
console.info('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>
«n», которое вы получаете, является следствием использования JSON.stringify. Вы не должны называть это.
Также:
replace
для "\n"jQuery
вместо ready
.jQuery(function($) {
$("button").on("click", function() {
var comment_raw = $("#comment").val();
$("#comment").val(
comment_raw.replace(/([^\w\s]|_)+/g, " ")
.replace(/\s+/g, " ")
.trim()
);
});
});
<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>
<button>clean</button>
И это выглядит немного проще, если вы используете match вместо replace:
jQuery(function($) {
$("button").on("click", function() {
var comment_raw = $("#comment").val();
$("#comment").val(
(comment_raw.match(/[a-z0-9]+/gi) || []).join(" ")
);
});
});
<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>
<button>clean</button>
Почему вы звоните JSON.stringify на строку?