I have this code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>sss</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type='text/javascript'>
function isAlphabet(obj){
var alphaExp = /[^a-z0-9_-]+/;
if(!obj.value.match(alphaExp)){
return true;
}
else{
alert('the bad symbols');
obj.focus();
return false;
}
}
</script>
</head>
<body>
<form action="/">
<input type='text' id='letters' onblur="isAlphabet(this)"/>
</form>
</body>
</html>
And I want to show an Alert() displaying only those characters for which validation fails.
For example :
If an input contains symbols like " #abc " , the Alert Message should show only "#". How can this be done?
Here's a simple way to do it... it's not be the most efficient though:
function isAlphabet(obj)
{
var val = obj.value;
var alphaExp = /[^a-z0-9_-]+/;
var valid = true;
var badchars = "";
for( a = 0; a < val.length; a++ )
{
if(val[a].match(alphaExp))
{
badchars += "," + val[a];
valid = false;
}
}
if( !valid )
{
alert("The following characters are not allowed: " + badchars.substr(1));
obj.focus();
}
return valid;
}
Use a regular expression which matches the allowed characters to get a string where those are removed. If the string contains anything, the validation fails:
function isAlphabet(obj) {
var alphaExp = /[a-z0-9_-]+/g;
var illegal = obj.value.replace(alphaExp, '');
if (illegal.length){
alert('Input contains the characters '+illegal+' which are not allowed.');
obj.focus();
return false;
} else {
return true;
}
}
In this case, you are matching characters that do not fall into the supplied ranges. Therefore, you can put the matched text into a backreference and use that.
Alternatively, you can construct a Regexp object and use it's lastMatch property.
You could matchall on regex which contains all the prohibited symbols (like your alphaExp), and then concatenate the matches.
if you use the g modifier, you can get .match() to return you an array of matches (invalid chars in your case) then you can just display them.
see "String.match(pattern)" about 1/3 down this page: http://evolt.org/regexp_in_javascript
var str = "Watch out for the rock!".match(/r?or?/g)
str then contains ["o","or","ro"]
Related
The below script returns the following into my html:
"3.9 °C {alarm,unackedAlarm}"
I would like to remove the "{alarm,unackedAlarm}" section so it just shows the temperature value. I believe I need to use a substring to achieve this but I cannot work out where to place it?
Thanks
<script src="https://requirejs.org/docs/release/2.3.6/minified/require.js" ></script>
require(['baja!', 'dialogs'], function (baja, dialogs) {
var sub = new baja.Subscriber();
sub.attach('changed', function(prop) {
if(prop.getName() === 'value');
{
document.getElementById("oat").innerHTML = ( this.get(prop));
}
});
baja.Ord.make('station:|slot:/BajaScriptExamples/Components/Ramp/out/value').get({ subscriber: sub});
});
'''
I would suggest using the regex approach just in case the number of characters change.
function extract(text) {
const pattern = /^(.*) {.*}$/g;
const match = [...text.matchAll(pattern)];
if (match.length == 0 || match[0].length == 0) {
console.error("text does not match");
return;
}
return match[0][1];
}
console.log(extract("3.9 °C {alarm,unackedAlarm}"));
The main idea here is to catch any string that follows this pattern (.*) {.*} and return what is in contained between the parenthesis (group).
The requirement of extracting specific part of a string can be done easily by using the split() function of Javascript.
Here are working examples using split:
Example 1: Split the string at blank spaces and print the first two parts.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var str = "3.9 °C {alarm,unackedAlarm}"
var result = str.split(" ")
document.getElementById("demo").innerHTML = (result[0] + " " + result[1])
</script>
</body>
</html>
Example 2: Split the string at '{' and print the first part.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var str = "3.9 °C {alarm,unackedAlarm}"
var result = str.split("{")
document.getElementById("demo").innerHTML = (result[0].trim())
</script>
</body>
</html>
Output:
3.9 °C
More information:
https://www.w3schools.com/jsref/jsref_split.asp
I wrote a regex tester in JS. However, it appears that for some regexes, I get multiple matches.
For example, if for the content hello, world, the regex hello.* is given, the it is reported to match hello, world. However, if the regex is now set to (hello|goodbye).* then the reported matches are hello, world and hello, whereas it should be hello, world only.
<!DOCTYPE html>
<html>
<head>
<title>Regex tester</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<script type="text/javascript">
function resetform() {
document.getElementById("results").innerHTML = "";
}
function escapetags(str) {
return (str.replace('&','&').replace('<', '<').replace('>', '>'));
}
function check() {
if (!document.form1.re.value) {
document.getElementById("results").innerHTML = '<p style="color:red"><b>Error: No regular expression specified</b></p>';
return;
}
if (!document.form1.str.value) {
document.getElementById("results").innerHTML = '<p style="color:red"><b>Error: No content specified</b></p>';
return;
}
var pattern,
modifiers = "";
if (document.form1.nocase.checked) {
modifiers = "i";
}
if (document.form1.global.checked) {
modifiers = modifiers + "g";
}
try {
if (modifiers) {
pattern = new RegExp(document.form1.re.value, modifiers);
} else {
pattern = new RegExp(document.form1.re.value);
}
} catch (excpt) {
document.getElementById("results").innerHTML = '<p style="color:red"><b>Error: Invalid regular expression</b></p>';
return;
}
var matches = pattern.exec(document.form1.str.value);
if (matches == null) {
document.getElementById("results").innerHTML = '<p><b>Regular expression did not match with content<b></p>';
} else {
document.getElementById("results").innerHTML = '<p><b>Regular expression matched with content</b></p><p>Matches:</p>';
for (var index = 0; index < matches.length; index++) {
document.getElementById("results").innerHTML += escapetags(matches[index]) + '<br>';
}
}
}
</script>
<h1>Regex tester</h1>
<form name="form1">
<p>Regex:</p>
<input type="text" name="re" size="65"><br>
<input type="checkbox" name="nocase">Case insensitive
<input type="checkbox" name="global">Global
<p>Content:</p>
<textarea name="str" rows="8" cols="65"></textarea><br><br>
<input type="button" value="Check" onclick="check();">
<input type="button" value="Reset" onclick="reset();resetform();">
</form>
<div id="results"></div>
</body>
</html>
Can anyone help me find the problem in my code?
Thanks in advance.
"(hello|goodbye). then the reported matches are hello, world and hello*"
No, the second "match" is just the result of your capturing group (what's between the parenthesis). Ignore it, or make the group non-capturing: (?:hello|goodbye)
The .exec() method of the JavaScript regex will return the entire matched string as the first element and then any captured groups as subsequent elements. When you use the regex:
(hello|goodbye).*
The brackets define a capture group, so your returned array will be
[0] = hello, world
[1] = hello
As Loamhoof suggest below, you can add ?: to make a group non-capturing if that is not desirable.
I think you want something like this,
var a = new RegExp("hello, world"); //or your string
var b = "hello, world";
if(a.test(b)){
//do your stuff
}
else{
//do your stuff
}
it will only match for the given pattern.
I wrote this function which takes in a word as input and puts it in a <b> tag so that it would be bold when rendered in HTML. But when it actually does get rendered, the word is not bold, but only has the <b> tag arround it.
Here is the function:
function delimiter(input, value) {
return input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3');
}
On providing the value and input, e.g. "message" and "This is a test message":
The output is: This is a test <b>message</b>
The desired output is: This is a test message
Even replacing the value with value.bold(), returns the same thing.
EDIT
This is the HTML together with the JS that I m working on:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<script>
function myFunction(){
var children = document.body.childNodes;
for(var len = children.length, child=0; child<len; child++){
if (children[child].nodeType === 3){ // textnode
var highLight = new Array('abcd', 'edge', 'rss feeds');
var contents = children[child].nodeValue;
var output = contents;
for(var i =0;i<highLight.length;i++){
output = delimiter(output, highLight[i]);
}
children[child].nodeValue= output;
}
}
}
function delimiter(input, value) {
return unescape(input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3'));
}
</script>
</head>
<body>
<img src="http://some.web.site/image.jpg" title="knorex"/>
These words are highlighted: abcd, edge, rss feeds while these words are not: knewedge, abcdefgh, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
I'm basically getting the result of the delimiter function and changing the nodeValue of a child node.
Is it possible there is something wrong with the way I'm taking back what the function is returning to me?
This is what I do:
children[child].nodeValue = output;
You need to have the markup processed as HTML, instead of being just set to replace existing content in a text node. For this, replace the statement
children[child].nodeValue= output;
by the following:
var newNode = document.createElement('span');
newNode.innerHTML = output;
document.body.replaceChild(newNode, children[child]);
Why is my code picking up the following error?
Line 32, Column 14: character "<" is the first character of a delimiter but occurred as data
for(i=0; i <= length; i++) {
This message may appear in several cases:
You tried to include the "<" character in your page: you should escape it as "<"
You used an unescaped ampersand "&": this may be valid in some contexts, but it is recommended to use "&", which is always safe.
Another possibility is that you forgot to close quotes in a previous tag.
Line 32, Column 14: StartTag: invalid element name
for(i=0; i <= length; i++) {
Code:
<script type="javascript">
function randomRange(minVal,maxVal)
{
var randVal = minVal+(Math.random()*(maxVal-minVal));
return (Math.floor(randVal));
}
function GetCaptcha() {
var encStr = "123456789ABCDEFGHJKMNPQRSTUVWXYZ";
var length = randomRange(4,8);
var result = "";
var i = "";
var char = "";
for(i=0; i <= length; i++) {
char = encStr.substr(randomRange(1,encStr.length),1);
result += char;
}
return result;
}
function InitCaptcha() {
var hidFld = document.MyForm.captchaHidFld;
str = GetCaptcha();
hidFld.value = str;
document.getElementById('captchaTxt').innerHTML = str;
document.getElementById('captchaBtn').value = str;
}
function ValidateCaptcha (theForm) {
var inpStr = (document.MyForm.captchaInpFld.value).toUpperCase();
var captStr = document.MyForm.captchaHidFld.value;
if (inpStr.length == captStr.length)
{
if (inpStr.match(captStr)) { return true; }
}
return false;
}
function cmdSubmit(theForm)
{
if (!ValidateCaptcha(theForm))
{
alert ("Please enter valid CAPTCHA Code.");
return false;
}
if (theForm.name.value == "")
{
alert ("Please enter your name.");
theForm.name.focus();
return false;
}
if (theForm.email.value == "")
{
alert ("Please enter your e-mail address.");
theForm.email.focus();
return false;
}
return true;
}
</script>
With that transitional XHTML DOCTYPE you'll need to enclose inline Javascript and CSS like this:
<script type="text/javascript">
//<![CDATA[
/* script here */
//]]>
</script>
Compare these results:
this is invalid
this validates
What are you using to validate this? You could always include the javascript as an external javascript file to get around this?
Also: Make sure the script tag is inside a <head> or <body> element?
Your code looks correct. If you bebug the code partially, i.e. GetCaptcha() using firebug, you will be able to track the error quickly.
or Post the HTML related to this code :)
How to check if a url or url pattern is presnt or not in a string using javascript.
<script language="javascript">
var str="http://localhost/testprj?test=123213123";
var s=location.href;
if(s.match('/http://localhost/testprj?test=1232/'){
alert('welcome!!');
}
</script>
what i need is to check the url pattern.
complete code
<html>
<head>
</head>
<body>
<style>
.active{
color:#009900;
font-weight:bold;
}
</style>
<div id="menu">
<ul><li>
<ul><li> 0
<a href="html.html" >1</a>
2
</li>
</ul></li>
</ul>
</div>
<script language="javascript">
var c=document.getElementById('menu').getElementsByTagName('a').length;
var v=document.getElementById('menu').getElementsByTagName('a');
var s=location.href;
//alert(s.match('html'));
for(var i=0;i<c;i++){
//alert('href'+v[i].className);
if(v[i].href==location.href){
v[i].className='active';
}
}
</script>
</body>
</html>
this is working fine , but if the get params are cause some problms...
like page.php?page=userlist
works fine
but
like page.php?page=userlist&id=121221
this is the base link url
link
For pattern checking, you will want to look into regular expressions.
What particular pattern do you want to check for? If you just want to check whether a string is a URL, the following code should do:
var myString = "http://blah.com/helloworld/";
if (myString.match(/http:\/\//)) {
alert("'myString' is a URL.");
}
Steve
/http:\/\/localhost\/testprj\?test=1232/.test(s)
I think you just had some minor syntax issues:
var re = /http:\/\/localhost\/testprj\?test=1232/
var s=location.href;
if(s.match(re)) {
alert('welcome!!');
}
note that regular expressions are a data type of their own in javascript: no quotes or anything, just / delimeters
Yes finaly i got the solution
i used the functions
for(var i=0;i<len;i++){
if(strstr(url,a[i].href)) {
a[i].className='active';
}
}
function strstr( url, href) {
var pos = 0;
url += '';
pos = url.indexOf( href );
if (pos == -1) {
return false;
}
else{
if(strcmp(url,href)==0)
return 1;
}
}
function strcmp ( str1, str2 ) {
return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
}
like this way, its working fine!!!
Thank you