Sil*_*fer 4 html javascript regex jquery
我正在尝试验证此content editable值,但是如果您应用多个空格,它将无法正常工作。这regex怎么了?
var regex = /^([A-zñÑáéíóú&;0-9 ]{0,100})$/;
$("button").on("click", function() {
if (regex.test($("#editable").text()) ) {
console.log("valid");
}
});Run Code Online (Sandbox Code Playgroud)
button {
display: block;
margin-top: 10px;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="editable" contenteditable="true" contenteditable="plaintext-only" max="100" class="font-italic">Editable</span>
<button>Check</button>Run Code Online (Sandbox Code Playgroud)
The issue is not in the regex: https://regex101.com/r/QP49FU/1
Everything seems to work if you remove the extra contenteditable="true" from your <span> tag:
var regex = /^([A-zñÑáéíóú&;0-9 ]{0,100})$/;
$("button").on("click", function() {
if (regex.test($("#editable").text()) ) {
console.log("valid");
}
});Run Code Online (Sandbox Code Playgroud)
button {
display: block;
margin-top: 10px;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="editable" contenteditable="plaintext-only" max="100" class="font-italic">Editable</span>
<button>Check</button>Run Code Online (Sandbox Code Playgroud)
But since contenteditable="plaintext-only" is not standardized, you should just remove that and edit the regex to accept the 'NO-BREAK SPACE' (U+00A0), because your original code will convert multiple spaces to those. So just add that to your character pattern:
var regex = /^([A-zñÑáéíóú&;0-9\u00a0 ]{0,100})$/;
$("button").on("click", function() {
if (regex.test($("#editable").text()) ) {
console.log("valid");
}
});Run Code Online (Sandbox Code Playgroud)
button {
display: block;
margin-top: 10px;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="editable" contenteditable="true" max="100" class="font-italic">Editable</span>
<button>Check</button>Run Code Online (Sandbox Code Playgroud)
Using \s in the pattern is subjectively bad, because then the pattern accepts all kinds of whitespace characters, including 'FORM FEED (FF)' (U+000C) and 'LINE TABULATION' (U+000B)', this might not be desirable.