i have a little problem with .search
this is the code
// filter - posts
jQuery('.filter_by').live('click',function(){
var target_fi = jQuery(this);
var target_cat = target_fi.parents('.cat').children('.namechanger').val();
target_fi.next().fadeIn(100);
var cat_all = target_fi.prev().find("option").each(function(i){
if(jQuery(this).attr('data-cats').search(target_cat) == -1){
jQuery(this).css({"display":"none"});
}
});
});
I want to use the variable target_cat with .search
I can't do this .search(/target_cat/)
If you want to make a regular expression out of the string value of target_cat, then you can do this:
var mySearchTerm = new RegExp(target_cat);
...
if(jQuery(this).attr('data-cats').search(mySearchTerm) == -1){
You need to create RegExp object and pass that to search method
if(jQuery(this).attr('data-cats').search(new RegExp(target_cat)) == -1 )){
...
}
To convert anything into a regular expression, simply drop it into the constructor:
var something = "foobar";
var expression = new RegExp(something, 'i');
note the second argument for flags. See RegExp for more info on the constructor and Regular Expressions for details on how things work.
If your something contains "special characters" (such as |, ?, {) you need to escape them, if you want them to be meant literally (/foo?/ vs. /foo\?/). Here's a function that'll esacpe all relevant characters for you:
function escapeRegEx(string) {
return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}
You are using jQuery.live, but should use jQuery.on instead
You are using .search() when .match() suffices
You are using the explicit jQuery(this).css({"display":"none"}); when jQuery(this).hide(); suffices
note that you are repeating jQuery(this) in your loop - one should be enough - variables are your friends.
Related
Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);
Let's say I have a string:
"__3_"
...which I would like to turn into:
"__###_"
basically replacing an integer with repeated occurrences of # equivalent to the integer value. How can I achieve this?
I understand that backreferences can be used with str.replace()
var str = '__3_'
str.replace(/[0-9]/g, 'x$1x'))
> '__x3x_'
And that we can use str.repeat(n) to repeat string sequences n times.
But how can I use the backreference from .replace() as the argument of .repeat()? For example, this does not work:
str.replace(/([0-9])/g,"#".repeat("$1"))
"__3_".replace(/\d/, function(match){ return "#".repeat(+match);})
if you use babel or other es6 tool it will be
"__3_".replace(/\d/, match => "#".repeat(+match))
if you need replace __11+ with "#".repeat(11) - change regexp into /\d+/
is it what you want?
According https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
str.replace(regexp|substr, newSubStr|function)
and if you use function as second param
function (replacement)
A function to be invoked to create the new substring (to put in place of the >substring received from parameter #1). The arguments supplied to this function >are described in the "Specifying a function as a parameter" section below.
Try this:
var str = "__3_";
str = str.replace(/[0-9]+/, function(x) {
return '#'.repeat(x);
});
alert(str);
Old fashioned approach:
"__3__".replace(/\d/, function (x) {
return Array(+x + 1).join('#');
});
Try this:
var str = "__3_";
str = str.replace(/[0-9]/g,function(a){
var characterToReplace= '#';
return characterToReplace.repeat(a)
});
Why doesn't the following jQuery code work?
$(function() {
var regex = /\?fb=[0-9]+/g;
var input = window.location.href;
var scrape = input.match(regex); // returns ?fb=4
var numeral = /\?fb=/g;
scrape.replace(numeral,'');
alert(scrape); // Should alert the number?
});
Basically I have a link like this:
http://foo.com/?fb=4
How do I first locate the ?fb=4 and then retrieve the number only?
Consider using the following code instead:
$(function() {
var matches = window.location.href.match(/\?fb=([0-9]+)/i);
if (matches) {
var number = matches[1];
alert(number); // will alert 4!
}
});
Test an example of it here: http://jsfiddle.net/GLAXS/
The regular expression is only slightly modified from what you provided. The global flag was removed, as you're not going to have multiple fb='s to match (otherwise your URL will be invalid!). The case insensitive flag flag was added to match FB= as well as fb=.
The number is wrapped in curly brackets to denote a capturing group which is the magic which allows us to use match.
If match matches the regular expression we specify, it'll return the matched string in the first array element. The remaining elements contain the value of each capturing group we define.
In our running example, the string "?fb=4" is matched and so is the first value of the returned array. The only capturing group we have defined is the number matcher; which is why 4 is contained in the second element.
If you all you need is to grab the value of fb, just use capturing parenthesis:
var regex = /\?fb=([0-9]+)/g;
var input = window.location.href;
var tokens = regex.exec(input);
if (tokens) { // there's a match
alert(tokens[1]); // grab first captured token
}
So, you want to feed a querystring and then get its value based on parameters?
I had had half a mind to offer Get query string values in JavaScript.
But then I saw a small kid abusing a much respectful Stack Overflow answer.
// Revised, cooler.
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match ?
decodeURIComponent(match[1].replace(/\+/g, ' '))
: null;
}
And while you are at it, just call the function like this.
getParameterByName("fb")
How about using the following function to read the query string parameter in JavaScript:
function getQuerystring(key, default_) {
if (default_==null)
default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
and then:
alert(getQuerystring('fb'));
If you are new to Regex, why not try Program that illustrates the ins and outs of Regular Expressions
The replace function returns the new string with the replaces, but if there weren't any words to replace, then the original string is returned. Is there a way to know whether it actually replaced anything apart from comparing the result with the original string?
A simple option is to check for matches before you replace:
var regex = /i/g;
var newStr = str;
var replaced = str.search(regex) >= 0;
if(replaced){
newStr = newStr.replace(regex, '!');
}
If you don't want that either, you can abuse the replace callback to achieve that in a single pass:
var replaced = false;
var newStr = str.replace(/i/g, function(token){replaced = true; return '!';});
As a workaround you can implement your own callback function that will set a flag and do the replacement. The replacement argument of replace can accept functions.
Comparing the before and after strings is the easiest way to check if it did anything, there's no intrinsic support in String.replace().
[contrived example of how '==' might fail deleted because it was wrong]
Javascript replace is defected by design. Why? It has no compatibility with string replacement in callback.
For example:
"ab".replace(/(a)(b)/, "$1$2")
> "ab"
We want to verify that replace is done in single pass. I was imagine something like:
"ab".replace(/(a)(b)/, "$1$2", function replacing() { console.log('ok'); })
> "ab"
Real variant:
"ab".replace(/(a)(b)/, function replacing() {
console.log('ok');
return "$1$2";
})
> ok
> "$1$2"
But function replacing is designed to receive $0, $1, $2, offset, string and we have to fight with replacement "$1$2". The solution is:
"ab".replace(/(a)(b)/, function replacing() {
console.log('ok');
// arguments are $0, $1, ..., offset, string
return Array.from(arguments).slice(1, -2)
.reduce(function (pattern, match, index) {
// '$1' from strings like '$11 $12' shouldn't be replaced.
return pattern.replace(
new RegExp("\\$" + (index + 1) + "(?=[^\\d]|$)", "g"),
match
);
}, "$1$2");
});
> ok
> "ab"
This solution is not perfect. String replacement itself has its own WATs. For example:
"a".replace(/(a)/, "$01")
> "a"
"a".replace(/(a)/, "$001")
> "$001"
If you want to care about compatibility you have to read spec and implement all its craziness.
If your replace has a different length from the searched text, you can check the length of the string before and after. I know, this is a partial response, valid only on a subset of the problem.
OR
You can do a search. If the search is successfull you do a replace on the substring starting with the found index and then recompose the string. This could be slower because you are generating 3 strings instead of 2.
var test = "Hellllo";
var index = test.search(/ll/);
if (index >= 0) {
test = test.substr(0, index - 1) + test.substr(index).replace(/ll/g, "tt");
}
alert(test);
While this will require multiple operations, using .test() may suffice:
const regex = /foo/;
const yourString = 'foo bar';
if (regex.test(yourString)) {
console.log('yourString contains regex');
// Go ahead and do whatever else you'd like.
}
The test() method executes a search for a match between a regular expression and a specified string. Returns true or false.
With indexOf you can check wether a string contains another string.
Seems like you might want to use that.
have a look at string.match() or string.search()
After doing any RegExp method, read RegExp.lastMatch property:
/^$/.test(''); //Clear RegExp.lastMatch first, Its value will be ''
'abcd'.replace(/bc/,'12');
if(RegExp.lastMatch !== '')
console.log('has been replaced');
else
console.log('not replaced');
In most languages like C# for example given a string you can test (boolean) if that string contains another string, basically a subset of that string.
string x = test2;
if(x.contains("test"))
// do something
How can I do this in a simple way with Javascript/Jquery?
This is done with indexOf, however it returns -1 instead of False if not found.
Syntax
string.indexOf(searchValue[, fromIndex])
Parameters
searchValue -
A string representing the value to search for.
fromIndex -
The location within string to start the search from. It can be any integer between 0 and the length of string. The default value is 0.
Return
The first index in string at which the start of the substring can be found, or -1 if string does not contain any instances of the substring.
As Paolo and cletus said, you can do it using indexOf().
Valid to mention is that it is a javascript function, not a jQuery one.
If you want a jQuery function to do this you can use it:
jQuery.fn.contains = function(txt) { return jQuery(this).indexOf(txt) >= 0; }
The indexOf operator works for simple strings. If you need something more complicated, it's worth pointing out that Javascript supports regular expressions.
A simple contains can also be useful for example:
<div class="test">Handyman</div>
$(".test:contains('Handyman')").html("A Bussy man");
A working example, using just indexOf and jQuery
// Add span tag, if not set
$(document).ready(function(c) {
$('div#content ul.tabs li a').each(function(c){
// Add span wrapper if not there already
if( $(this).html().indexOf('span') == -1){
$(this).html('<span class="tab">' + $(this).html() + '</span>');
}
});
});
DT
Try to implement this
function function1() {
var m = document.all.myDiv.contains(myB);
if (m == true){
m = "YES"
} else {
m = "NO"
}
alert(m)
}