I have the following fiddle:
jsfiddle
The function:
$('#testbutton').on("click", function(){
test();
});
function test()
{
var data = [];
data['article'] = "monablanko";
data['specialarticle'] = ["blanko", "bbsooel"];
var tmp = data['specialarticle'].join("|");
if( data['article'].match( /(tmp)/ ) )
{
$('#result').html("I found a match");
}
else
{
$('#result').html("I didn't found a match");
}
}
I didn't found a match with this function. Where is my error? The typeof tmp is string when i use
console.log(typeof tmp);
when i write
if( data['article'].match( /(blanko|bbsooel)/ ) )
then i find a match.
You're matching against the string literal "tmp", not against the value contained inside the variable tmp. Try it like this:
data['article'].match( new RegExp("(" + tmp + ")") )
eg: http://jsfiddle.net/4K8Km/
You need to create a RegExp to match your string before:
$('#testbutton').on("click", function(){
test();
});
function test(){
var data = [];
data['article'] = "monablanko";
data['specialarticle'] = ["blanko", "bbsooel"];
var tmp = new RegExp('('+data['specialarticle'].join("|")+')');
if( data['article'].match( tmp ) )
{
$('#result').html("I found a match");
}
else
{
$('#result').html("I didn't found a match");
}
}
Just one more tip: if you don't need to collect a match, but just to test if the string has that RegExp I would suggest to use test instead of match:
tmp.test(data['article']);
rather than
data['article'].match(tmp);
Related
When I run this code:
var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
var foundUrl = foundUrlString[1];
I get an error if there are no matches on the page:
Result of expression 'foundUrlString' [null] is not an object
How can I get "false" when there are no matches instead of this error?
Going off of what you have, you could add a "truthy" check on the second line:
var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
var foundUrl = !!foundUrlString && foundUrlString[1];
That will leave foundUrl either as a matched string or false.
Check null to print false or true.
var savedPage = '';
var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
var foundUrl = foundUrlString == null ? false : true;
console.log(foundUrl );
Here is an example with try and catch which may help you:
function regex(savedPage) {
try {
var foundUrlString = savedPage.match(/og:url.*="(http.*\.com)/i);
return foundUrlString[1];
} catch (error) {
return false;
}
}
var savedPage1 = '<link property="og:url" content="http://test.com/test">';
console.log('savedPage1',regex(savedPage1));
var savedPage2 = '<link content="http://test.com/test">';
console.log('savedPage2',regex(savedPage2));
You need to understand what's the purpose of String.prototype.match. The function match will return an array with the whole set of matched groups in your regexp. So, if you want to validate a string, the best way is using the function RegExp.prototype.test.
Use the function RegExp.prototype.test from regexp:
let savedPage = "EleFromStack";
console.log(/og:url.*="(http.*\.com)/i.test(savedPage));
I need your your help,
For some strange reason, when my var str is set to "OTHER-REQUEST-ASFA" the matched key comes back as "ASF" as opposed to "ASFA"
How can I get the returned output key of "ASFA" when my str is "OTHER-REQUEST-ASFA"
function test() {
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
for (var key in filenames) {
if (str.indexOf(key) != -1) { alert(filenames[key]) }
}
}
You could switch from
str.indexOf(key)
to
key.indexOf(str)
function test() {
var str = "OTHER-REQUEST-ASFA",
filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
},
key;
for (key in filenames) {
if (key.indexOf(str) != -1) {
console.log(filenames[key]);
}
}
}
test();
To answer why it's not working as you want...
You've got:
str.indexOf(key)
This checks for the first instance of key in str.
So in your loop, key first equals OTHER-REQUEST-ASF which is part of OTHER-REQUEST-ASFA, so the condition is true.
However, to do what you want to do, if you know the pattern is always going to be OTHER-REQUEST-XYZ, the easiest way is to use split():
str.split('-')[2]
will always return the last section after the last -
cause "OTHER-REQUEST-ASFA".indexOf("OTHER-REQUEST-ASF") will not return -1, so it will show "ASF"
You can also use static method Object.keys() to abtain array of keys
var test = () =>{
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
Object.keys(filenames).forEach(x => {
if ( x.indexOf(str) !== -1)
console.log(filenames[str]);
});
}
test();
i got a question:
This code snippet works great:
$(document).ready(function(){
var pathname = window.location.pathname;
if(pathname.indexOf( 'word1' ) > -1){
// do something
}
});
But if i want to check for array of word´s it doesnt work:
$(document).ready(function(){
var myArray1 = new Array( "word1","word2","word3","word4" );
var pathname = window.location.pathname;
if(pathname.indexOf( myArray1 ) > -1){
// never executed! why?
}
});
Anybody could help with this problem? Greetings!
jQuery has a built in method for that, $.inArray :
$(document).ready(function(){
var pathname = window.location.pathname;
if ( $.inArray(pathname, ["word1","word2","word3","word4"] ) != -1 ) {
// do stuff
}
});
then there's regex
$(document).ready(function(){
if ( /(word1|word2|word3|word4)/.test(window.location.pathname) ) {
// do stuff
}
});
If you want to test pathname against an array of values, I suggest looping. You cannot send in an array object as an argument to the indexOf() method. You can only send strings.
$(document).ready(function(){
var myArray1 = new Array( "word1","word2","word3","word4" );
var pathname = window.location.pathname;
for(stringy in myArray1){
if(pathname.indexOf( stringy ) > -1){
console.log('Match Found');
}
}
});
Look here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
You could use jQuery.grep() for this:
if ($.grep(myArray1, function(word) {
return pathname.indexOf(word) != -1;
})) {
// do something
}
Or, use native functions:
if (myArray1.some(function(word) {
return pathname.indexOf(word) != -1;
})) {
// do something
}
indexOf looks for occurrences of a given string in another string. So you can't invoke it with an array as parameter. You must invoke it several times, each one with a string as parameter.
$(document).ready(function(){
var myArray1 = new Array( "word1","word2","word3","word4" );
var pathname = window.location.pathname;
for(var i=0; i<myArray1.length; i++) {
if(pathname.indexOf( myArray1[i] ) > -1){
// will be executed
}
}
});
string.indexOf doesn't take array as a parameter, you should handle it yourself,
Ok I will make it a little bit different, you can also do this with Regex,
$(document).ready(function(){
var myArray1 = new Array( "word1","word2","word3","word4" );
var pathname = window.location.pathname;
if (pathname.match(new RegExp(myArray1.join("|")))) {
// yes, there is at least one match.
}
});
I don't know whether if you want it to match all words in the array.
I made a way to test n quantities of pathnames.
import pathToRegexp from 'path-to-regexp';
const ALLOWED_PATHS = [
'test',
'test/:param'
]
const allowed = ALLOWED_PATHS.map((path) => {
const regex = pathToRegexp(path)
return regex.test(window.location.pathname);
});
if(allowed.some(Boolean)) {
// Match
} else {
// Not Match
}
...
Hope this helps you!
My string is :<div>2</div><div>3</div><div>4</div><div>5</div><div><br></div>
I need to get 2,3,4,5, in an array using Javascript ie.anything between <div></div>
Whats the most elegant way to do this?
To match anything between <div> and </div>
var a, r=[];
while((s=str.indexOf("<div>"))!=-1){
e=str.indexOf("</div>");
a=str.substring(s+5, e);
if(a) r.push(a);
str=str.substr(e+6);
}
Another easier method
var r = str.match(/<div>.*?<\/div>/gi).map(function(i){
return i.replace(/<div>(.*?)<\/div>/gi, "$1");
});
If it was just digits (like in your initial question) use this
var str = "<div>2</div><div>3</div><div>4</div><div>5</div><div><br></div>";
var num = str.match(/\d+/g)
try the below code
var obj = $("div").map(function(index,value){
return $(this).html();
})
alert( "hi" +obj[0]);
http://jsfiddle.net/F9MQr/12/
For any value you could;
var s = "<div>2</div><div>3</div><div>4</div><div>5</div><div><br></div>";
var a = [];
$.each($(s).filter("div"), function() {
$(this).text() !== "" && a.push($(this).text());
});
alert(a);
(This would ignore empty divs & return X for <div>X<br/></div>)
I'm looking for a jQuery plugin that can get URL parameters, and support this search string without outputting the JavaScript error: "malformed URI sequence". If there isn't a jQuery plugin that supports this, I need to know how to modify it to support this.
?search=%E6%F8%E5
The value of the URL parameter, when decoded, should be:
æøå
(the characters are Norwegian).
I don't have access to the server, so I can't modify anything on it.
function getURLParameter(name) {
return decodeURI(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
Below is what I have created from the comments here, as well as fixing bugs not mentioned (such as actually returning null, and not 'null'):
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
What you really want is the jQuery URL Parser plugin. With this plugin, getting the value of a specific URL parameter (for the current URL) looks like this:
$.url().param('foo');
If you want an object with parameter names as keys and parameter values as values, you'd just call param() without an argument, like this:
$.url().param();
This library also works with other urls, not just the current one:
$.url('http://allmarkedup.com?sky=blue&grass=green').param();
$('#myElement').url().param(); // works with elements that have 'src', 'href' or 'action' attributes
Since this is an entire URL parsing library, you can also get other information from the URL, like the port specified, or the path, protocol etc:
var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value');
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'
It has other features as well, check out its homepage for more docs and examples.
Instead of writing your own URI parser for this specific purpose that kinda works in most cases, use an actual URI parser. Depending on the answer, code from other answers can return 'null' instead of null, doesn't work with empty parameters (?foo=&bar=x), can't parse and return all parameters at once, repeats the work if you repeatedly query the URL for parameters etc.
Use an actual URI parser, don't invent your own.
For those averse to jQuery, there's a version of the plugin that's pure JS.
If you don't know what the URL parameters will be and want to get an object with the keys and values that are in the parameters, you can use this:
function getParameters() {
var searchString = window.location.search.substring(1),
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
return hash;
}
Calling getParameters() with a url like /posts?date=9/10/11&author=nilbus would return:
{
date: '9/10/11',
author: 'nilbus'
}
I won't include the code here since it's even farther away from the question, but weareon.net posted a library that allows manipulation of the parameters in the URL too:
Blog post: http://blog.weareon.net/working-with-url-parameters-in-javascript/
Code: http://pastebin.ubuntu.com/1163515/
You can use the browser native location.search property:
function getParameter(paramName) {
var searchString = window.location.search.substring(1),
i, val, params = searchString.split("&");
for (i=0;i<params.length;i++) {
val = params[i].split("=");
if (val[0] == paramName) {
return unescape(val[1]);
}
}
return null;
}
But there are some jQuery plugins that can help you:
query-object
getURLParam
Based on the 999's answer:
function getURLParameter(name) {
return decodeURIComponent(
(location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
);
}
Changes:
decodeURI() is replaced with decodeURIComponent()
[?|&] is added at the beginning of the regexp
Need to add the i parameter to make it case insensitive:
function getURLParameter(name) {
return decodeURIComponent(
(RegExp(name + '=' + '(.+?)(&|$)', 'i').exec(location.search) || [, ""])[1]
);
}
After reading all of the answers I ended up with this version with + a second function to use parameters as flags
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)','i').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
function isSetURLParameter(name) {
return (new RegExp('[?|&]' + name + '(?:[=|&|#|;|]|$)','i').exec(location.search) !== null)
}
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(top.window.location.href);
return (results !== null) ? results[1] : 0;
}
$.urlParam("key");
For example , a function which returns value of any parameters variable.
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
And this is how you can use this function assuming the URL is,
"http://example.com/?technology=jquery&blog=jquerybyexample".
var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');
So in above code variable "tech" will have "jQuery" as value and "blog" variable's will be "jquerybyexample".
You should not use jQuery for something like this!
The modern way is to use small reusable modules through a package-manager like Bower.
I've created a tiny module that can parse the query string into an object. Use it like this:
// parse the query string into an object and get the property
queryString.parse(unescape(location.search)).search;
//=> æøå
There's a lot of buggy code here and regex solutions are very slow. I found a solution that works up to 20x faster than the regex counterpart and is elegantly simple:
/*
* #param string parameter to return the value of.
* #return string value of chosen parameter, if found.
*/
function get_param(return_this)
{
return_this = return_this.replace(/\?/ig, "").replace(/=/ig, ""); // Globally replace illegal chars.
var url = window.location.href; // Get the URL.
var parameters = url.substring(url.indexOf("?") + 1).split("&"); // Split by "param=value".
var params = []; // Array to store individual values.
for(var i = 0; i < parameters.length; i++)
if(parameters[i].search(return_this + "=") != -1)
return parameters[i].substring(parameters[i].indexOf("=") + 1).split("+");
return "Parameter not found";
}
console.log(get_param("parameterName"));
Regex is not the be-all and end-all solution, for this type of problem simple string manipulation can work a huge amount more efficiently. Code source.
<script type="text/javascript">
function getURLParameter(name) {
return decodeURIComponent(
(location.search.toLowerCase().match(RegExp("[?|&]" + name + '=(.+?)(&|$)')) || [, null])[1]
);
}
</script>
getURLParameter(id) or getURLParameter(Id) Works the same : )
jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
example.com?param1=name¶m2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
//example params with spaces
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));
//output: Gold%20Coast
console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast
function getURLParameters(paramName)
{
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i=0;i<arrURLParams.length;i++)
{
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i=0;i<arrURLParams.length;i++)
{
if(arrParamNames[i] == paramName){
//alert("Param:"+arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
I created a simple function to get URL parameter in JavaScript from a URL like this:
.....58e/web/viewer.html?page=*17*&getinfo=33
function buildLinkb(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=parseInt(url.replace(param+"=",""));
alert(n+1);
}
buildLinkb("page");
OUTPUT: 18
Just in case you guys have the url like localhost/index.xsp?a=1#something and you need to get the param not the hash.
var vars = [], hash, anchor;
var q = document.URL.split('?')[1];
if(q != undefined){
q = q.split('&');
for(var i = 0; i < q.length; i++){
hash = q[i].split('=');
anchor = hash[1].split('#');
vars.push(anchor[0]);
vars[hash[0]] = anchor[0];
}
}
Slight modification to the answer by #pauloppenheim , as it will not properly handle parameter names which can be a part of other parameter names.
Eg: If you have "appenv" & "env" parameters, redeaing the value for "env" can pick-up "appenv" value.
Fix:
var urlParamVal = function (name) {
var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
return result ? decodeURIComponent(result[2]) : "";
};
This may help.
<script type="text/javascript">
$(document).ready(function(){
alert(getParameterByName("third"));
});
function getParameterByName(name){
var url = document.URL,
count = url.indexOf(name);
sub = url.substring(count);
amper = sub.indexOf("&");
if(amper == "-1"){
var param = sub.split("=");
return param[1];
}else{
var param = sub.substr(0,amper).split("=");
return param[1];
}
}
</script>