checking a pattern present in a string using javascript - javascript

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

Related

New to Javascript, could someone help me with this substring problem?

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

Word count in AngularJS

I am trying to write a quick program that counts the number of words in AngularJS. Basically a textarea in HTML and underneath it should display the number of words as the user inputs them.
So this is my HTML code:
<!doctype html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
<script src="wordcount.js"></script>
</head>
<body>
<div ng-controller="wordCount">
<label>Copy and Paste your text:</label><br>
<textarea cols="80" rows="20" ng-model="mytext"></textarea>
<hr>
<span>{{wordCount()}} word(s)</span>
</div>
</body>
</html>
And here is my Javascript file called wordcount.js (to count the number of words in a given string):
function wordCount($scope) {
$scope.numberofwords = function(s) {
s = document.getElementById("mytext").value;
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
return s.split(' ').length;
}
}
I basically found the above on http://www.mediacollege.com/internet/javascript/text/count-words.html
So I have probably not fully understood how to use AngularJS (and the JS code is probably wrong too) to update the number of words instantly. Right now it doesn't show anything but "words".
Does anyone have an idea?
One of correct way is to use a $scope function:
<body ng-controller="WCController">
<h3>World count</h3>
<div>total words: <span ng-bind="countOf(myText)"></span></div>
<textarea ng-model="myText"></textarea>
</body>
and at the controller:
$scope.countOf = function(text) {
var s = text ? text.split(/\s+/) : 0; // it splits the text on space/tab/enter
return s ? s.length : '';
};
You can test this on plunker:
http://run.plnkr.co/Mk9BjXIUbs8hGoGm/
Solution
update a wordCount property when myText changes.
use simple regexp in a String.prototype.match call.
use this updated wordCount scope property in your template.
Code
Your watcher should look like something like that:
$scope.$watch('myText', function(text) {
// no text, no count
if(!text) {
$scope.wordCount = 0;
}
// search for matches and count them
else {
var matches = text.match(/[^\s\n\r]+/g);
$scope.wordCount = matches ? matches.length : 0;
}
});
Important note
Why computing the count in a watcher ?
To prevent this count from being computed on each digestion, the way it is when you use such a wordCount() method call in your template !

.find doesn't work in jquery 1.4.2 and I can't figure out how to support it

I can't figure out how to write my code backwards to support jQuery 1.4.2. So I am perplexed trying to support older library files.
var n = this;
e(document).ready(function () {
var r = e("body").find(n);
r.attr("placeholder", t);
r.val(t);
n.focus(function () {
e(this).val("")
}).blur(function () {
var r = e(n);
if (r.val() == "") r.val(t)
})
})
You're overcomplicating your code. First, you don't need to use $(document).ready() inside of a plugin, you can let the developer using the plugin take care of that. Next, inside of a plugin, this is a jQuery object containing the selected elements. You should iterate over them then act on each one individually.
(function ($) {
$.fn.labelfixer = function (t) {
return this.each(function(){
var $this = $(this);
$this.attr("placeholder",t);
this.value = t;
$this.focus(function(){
if (this.value == t) {
this.value = "";
}
});
$this.blur(function(){
if (this.value == "") {
this.value = t;
}
});
});
};
})(jQuery);
Are you sure of this ? I have just binned out one example using 1.4.2 for find and it's working properly .
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body id='bd'>
<ul class="level-1">
<li class="item-i">I</li>
<li class="item-ii">II
<ul class="level-2">
<li class="item-a">A</li>
<li class="item-b">B
<ul class="level-3">
<li class="item-1">1</li>
<li class="item-2">2</li>
<li class="item-3">3</li>
</ul>
</li>
<li class="item-c">C</li>
</ul>
</li>
<li class="item-iii">III</li>
</ul>
</body>
</html>
JS:
$('li.item-ii').find('li').css('background-color', 'red');
Find the bin here :http://jsbin.com/INonAYo/1/edit
Yes, that would be correct. The .find() function was added in 1.6. You could upgrade jQuery or use the .find() using the CSS selector.
If you have the elements with unique .id elements, you could just change your .find function to call that:
.find('#' + n.id)
Another option, since you have 'this', is that you could just use the basic $(this):
var r = $(this);
Or, for your code r = e(this);
This might not be the most elegant solution, but you could check if the find function exists, and then add it to the jquery object if it does not.
Something like
if (!$.find) {
$.fn.find = function () {
// find function definition
};
}
edit: a better conditional:
var version = $.fn.jquery.split('.');
if (version[0] < 2 && version[1] <= 6 && version[2] < 4)
last edit: since jsfiddle doesn't have less than 1.6.4 jquery, i can't test this to verify, but I pulled the find function from google's cdn jquery 1.6.4, so the complete monkeypatch would be:
var version = $.fn.jquery.split('.');
if (version[0] < 2 && version[1] <= 6 && version[2] < 4) {
$.find = function( expr, context, isXML ) {
var set;
if ( !expr ) {
return [];
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
var match,
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
var left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace( rBackslash, "" );
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( "*" ) :
[];
}
return { set: set, expr: expr };
};

how to remove everything except numeric 1234567890 using javascript

i have the following javascript how and where to set so when it will get the data and shows in a textbox it will show only numeric values:
<script type="text/javascript">
function showData($sel){
var str='';
document.getElementById("demo").innerHTML;
for (var i=0;i<sel.options.length;i++){
str+=(str!='') ? ', '+sel.options[i].value : sel.options[i].value;
}
}
sel.form.selectedFruits.value = str;
}
</script>
i have multiple select dropdown and it has multiple values like Staff No and email so i dont want to show email in text box only staff no and even i dont want to remove email from values.
it is working fine except what i want to do :D
A simple solution, if you want to get only numbers from a string (or html in your example), will be :
var str= document.getElementById(id).innerHTML;
return str.replace(/[^0-9]/ig, '');
See this jsfiddle.
if I've gotten the point correctly try something like this
<script type="text/javascript">
function showData($sel){
var str=[];
document.getElementById("demo").innerHTML;
for (var i=0;i<sel.options.length;i++){
str[i]+=sel.options[i].value.replace(/\D/g, ''); // remove everything except digits
}
}
sel.form.selectedFruits.value = str.join();
}
</script>
<script type="text/javascript">
function showStaffno(sel){
var str='';
document.getElementById("demo").innerHTML;
for (var i=0;i<sel.options.length;i++){
if (sel.options[i].selected){
str+=(str!='') ? ', '+sel.options[i].value.replace(/\D/g, '') : sel.options[i].value.replace(/\D/g, '');
}
}
sel.form.selectedFruits.value = str;
}
</script>

Regexp JS from referrer

I need to check if a referrer has word "profile" i need to put profile/(.*?) in a var. How can I do it in js?
<script type="text/javascript">
var ref = document.referrer;
if( ~ref.indexOf("profile") ) {
alert('coincidence found!');
}
</script>
<script>
var str="Is this all there is?";
var patt1=/[^a-h]/g;
document.write(str.match(patt1));
</script>
Result :I,s, ,t,i,s, ,l,l, ,t,r, ,i,s,?
check link The [^abc] expression is used to find any character not between the brackets.
and this tooo link
var ref = document.referrer;
ref.match(/(?:profile).+/,(match)=> {
console.log(match)
})

Categories