I have the following code which works fine for english but not working for arabic. how can i use this code for arabic also. how can I serach it as a string
function highlightSearch() {
var text = document.getElementById("query").value;
var query = new RegExp("(\\b" + text + "\\b)", "gim");
var e = document.getElementById("nav-5-3-primary-ver").innerHTML;
var enew = e.replace(/(<h6>|<\/h6>)/igm, "");
document.getElementById("nav-5-3-primary-ver").innerHTML = enew;
var newe = enew.replace(query, "<h6>$1</h6>");
document.getElementById("nav-5-3-primary-ver").innerHTML = newe;
}
#nav-5-3-primary-ver h6{
background-color:#FF9;
color:#555;
}
<input name="query" id="query" type="text" size="30" maxlength="30">
<input name="searchit" type="button" value="Search" onClick="highlightSearch()">
<div id="nav-5-3-primary-ver">
hello i am this
</br>
اذا كان الجهاز خارج التغطية هل يتم تسجيل البيانات للسيارة؟
</div>
There's a gotcha with \b (in javascript at least) : the notion of "word" it uses (to detect word boundaries) is :
sequences of characters in the set [a-zA-Z0-9_] (latin alphanumerics, plus the _ char)
It won't work as you expect for other charsets (note : even latin diacritics - letters with accents or signs on them - don't work).
Choose some other way to chek that you matched a complete word :
as suggested in this answer : you can write a predicate that matches "a space character or ^ or $"
or match the word without boundaries, and for each match, inspect the characters prior and next to that match
Links to ECMAscript specifications :
Assertions in Regular Expressions
Word Character definition
Related
I'm trying to make a validation for my form with JavaScript. This is what I have done so far, and it works, but in the input "klassekode" needs to start with two letters and then one number.
My html code
<form class="form1" method="POST" id="registrerFagSkjema" action="registrerklasse.php" name="registrerFagSkjema" onSubmit="return validerRegistrerFag()">
Registrer klasse <br> <br>
Klassekode <br>
<input value="" type="text" name="fagkode" id="fagkode" onFocus="fokus(this)"
onBlur="mistetFokus(this)" onMouseOver="musInn(this)" onMouseOut="musUt()"
onChange="endreTilStoreBokstaver(this)"/ /><br>
Klassenavn <br>
<input value="" type="text" name="klassenavn" id="klassenavn" onFocus="fokus(this)"
onBlur="mistetFokus(this)" onMouseOver="musInn(this)" onMouseOut="musUt()" />
<input value="Registrer Klasse" type="submit" name="submit" id="submit" >
<input type="reset" value="Nullstill" id="reset" name="reset" onClick="fjernMelding()">
</form>
<div id="melding"></div>
My JavaScript code
function validate()
{
var klassekode = document.getElementById("klassekode");
var klassenavn = document.getElementById("klassenavn");
var feilmelding="";
//var firstTwoLetters = document.getElementById("klassekode").substring(0,2);
if(klassekode.value.trim()=="")
{
//alert("blank");
feilmelding="Fyll ut Klassekode";
document.getElementById("melding").style.color="red";
document.getElementById("melding").innerHTML=feilmelding;
klassekode.style.border = "solid 1px red";
return false;
}
else if ( klassekode.value.trim().length!=3)
{
//alert("klassekode for lang");
feilmelding="Klassekode må kun være 3 bokstaver";
document.getElementById("melding").style.color="red";
document.getElementById("melding").innerHTML=feilmelding;
klassenavn.style.border = "solid 1px red";
return false;
}
else if (klassenavn.value.trim()=="" )
{
//alert("blank");
feilmelding="Fyll ut Klassenavn";
document.getElementById("melding").style.color="red";
document.getElementById("melding").innerHTML=feilmelding;
klassenavn.style.border = "solid 1px red";
return false;
}
else { return true;}
}
You got the hang of substring, and you can use that the newer method isNaN (Not a Number) and divide your third character with 1. If it's a letter, isNaN will return "true" and if it's a number, it will return "false".
I would, however, recommend you to learn regular expressions, as it will benefit you tremendously in the future.
You basically create a pattern and then test a string against that pattern. If you find a match, then it's correct. I made a snippet below to demonstrate:
function validateInput() {
let inputElement = document.getElementById("namn");
let divElement = document.getElementById("comment");
var message = "not true";
let inputValue = inputElement.value.trim();
let pattern = new RegExp(/^[a-zøæ]{2}\d{1}/, "i");
if (isValid(inputValue, pattern)) {
message = "true"
}
divElement.innerHTML = message;
}
function isValid(str, pattern) {
return str.match(pattern);
}
<input id="namn" type="input" value="">
<input type="button" onclick="validateInput()" value="Validate" />
<div id="comment"></div>
This row needs explanation:
let pattern = new RegExp(/^\d{1}[a-zøæ]{2}/, "i");
The regular expression contains expressions that can be stringed together:
^: start at the beginning of the string.
[a-zøæ]{2}: 2 characters must be between a-z or contain ø or æ.
\d{1}: next following 1 character must be a digit.
The flag "i" makes the a-z case insensitive. Another way would be to don't add a flag, and instead write [a-zA-ZøØæÆ]
Regex to the rescue. You can add another else if statement as per the following:
else if (klassekode.value.trim().length !== 3) {
// after checking whether the string length is 3 characters...
} else if (!klassekode.value.trim().match(/^[a-z]{2}\d/i)) {
// apply validation warning styles
return false;
}
An explanation of the Regex:
^ - asserts position at the start of the string
[a-z] - matches an alphabetic character
{2} - matches exactly twice
\d - matches a digit (0-9) once
i - case insensitive match
I am not checking the string length again because your previous condition accounts for it.
Ensure to trim() the value before using it (e.g. before sending it to the backend for processing, etc.), because otherwise the leading/trailing spaces will be retained.
I have a from. User can fill an input field with text that contains special characters like \n, \t and etc. I have to replace these special characters and add it back as value of the input field.
for example:
user input is: hello, \n how are you doing? \t this is a sample text.
This is what I need: hello, newline how are you doing? tab this is a sample text.
I am using JQuery and Typescript 2.4
How about this?
$('#input').keyup(function () {
var val = $(this).val();
var replaceWithBr = val.replace(/\\n/g, '<br>');
var replaceWithTab = replaceWithBr.replace(/\\t/g, ' ');
$('#result').html(replaceWithTab);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input">
<div id="result"></div>
In the email input field I am checking for illegal characters using regex, like this:
$("#reg_email").keyup(function(event)
{
var regex = /[()-/+{|}\\[\]?!*+^$<>&#~"'%=_:;]/g;
if ($("#reg_email").val().match(regex))
{
$("#reg_email").notify("Illegal characters: \n( ) - / \\ + { } | [\ ] ? ! * + ^ $ < > & # ~ % = _ : ; '",{position:"right", className:"warn", autoHideDelay: autoHideDelay});
this.value = this.value.replace(regex, "");
}
});
Here is the markup:
<input id="reg_email" type="email" class="form-control placeholder" placeholder="" name="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" required>
But I've noticed that now I cannot enter a full stop character in the input field, and that is not what I want, since email addresses will contain a full stop. I am aware that '>' has the same keycode as a full stop, but currently I am struggling with finding another way.
How can I achieve this alternatively? Thanks
You have )-/ in your set, which creates a range that matches )*+,-./ (according to the ASCII table) and not just the characters )-/ literally. Escape the - or put it at the start or end of the character class as the examples below show:
[()\-/+{|}\\[\]?!*+^$<>&#~"'%=_:;] # escaped \-
[-()/+{|}\\[\]?!*+^$<>&#~"'%=_:;] # hyphen at start of class
[()/+{|}\\[\]?!*+^$<>&#~"'%=_:;-] # hyphen at end of class
I Have next pattern:
[a-z[A-Z]а-я[А-Я][0-9]їЇіІєЄ[-][,]_"/\ ]{0,483}
<input
id="<?= $field['id'];?>"
name="input"
<?php if (isset($field['regex'])) echo "pattern=".$field['regex'];?>
>
By this pattern I check data in field by javascript:
var decode_pattern = $(this).attr('pattern');
var reg = RegExp("^" + decode_pattern + "$");
But when i try to input (sdfzsdf) in field, regexp tell me - wrong.
Why?
I Have this pattern: [a-z[A-Z]а-я[А-Я][0-9]їЇіІєЄ[-][,]_"/\ ]{0,483}
JavaScript Regex syntax does't allow character classes in character classes. Maybe you meant
[a-zA-Zа-яА-Я0-9їЇіІєЄ,_"/\\ -]{0,483}
Your current regex is equivalent to /[a-z\[A-Z]а-я[А-Я]\dїЇіІєЄ-,_"\/ \]{0,483}/.
Also, since it contains a quote you will need to html-escape your attribute value:
echo 'pattern="'.htmlspecialchars($field['regex']).'"';
I'm a novice when it comes to Javascript.
I would like to improve the search in the script provided below.
I have the following code and currently when I type the phrase 'blue widgets' in search, it will only identify/find the checkbox if the phrase 'blue widgets' exits in sequence. For example, If I have a keyword phrase or sentence that contains 'blue cool widgets' and I search for 'blue widgets' it is unable to locate that even though blue and widgets both exist in my keyword phrase.
Could it be possible that if I search for a phrase with 2 or even 3 words in it, then it can find any keyword phrase/sentence on my page in which all words of my search phrase exist and then check the box (which the code already does). The only condition is that all the words of my search phrase have to exist in a sentence/string ?
I would very much appreciate if this solution can be found.
<html>
<head>
<script type="text/javascript">
function checkForWord( wordField )
{
var form = wordField.form;
var word = wordField.value.replace(/^\s+/,"").replace(/\s+$/,"").toLowerCase();
var inputs = form.getElementsByTagName("input");
for ( var e = 0; e < inputs.length; ++e )
{
var field = inputs[e];
if ( field.type == "checkbox" )
{
if ( field.value.toLowerCase().indexOf(word) >= 0 )
{
field.checked = true;
} else {
// OPTIONAL, if you do NOTwant to clear previously checked boxes, omit next line:
field.checked = false;
}
}
}
}
</script>
</head>
<body>
<form onsubmit="return false;">
Type a word: <input name="word" onchange="checkForWord(this);" />
<hr>
<label>
<input type="checkbox" name="keywords" value="This is an example sentence with blue and cool widgets not in order and my current script will not find it.
</label></br/>
<label>
<input type="checkbox" name="keywords" value="This sentence will be found if I search for blue widgets because its in this sentence">
All work and no play makes Jack
</label></br/>
<label>
<input type="checkbox" name="keywords" value="I would like for it to be able to find this sentence also since blue and widgets both words exist but are out of order.
</label></br/>
</form>
</body>
</html>
It would be the best to tokenize your search string (split it by words), execute each search independently (for every word) and then merge results.
/(?=.*blue)(?=.*widgets)/.test( phrase );
(?=...) is a look-ahead, meaning it only matches if the expression is matched somewhere further in the string. The nice part is that it doesn't consume the match, so the above will only match if you have "blue" and "widgets" at some point later in the string, but order doesn't matter.
Feel free to modify those to wrap with whitespace if necessary so that it only matches the entire word (e.g. wrap the words with \b)
To generate that regex dynamically:
var words = 'blue widgets';
new RegExp( '(?=.*' + words.split( /\W+/g ).join( ')(?=.*' ) + ')', 'i' )