This question already has answers here:
Match #(\w+) and replace in javascript
(2 answers)
Closed 6 years ago.
I have the following
function arrayInArray(chBox, values) {
try {
for (var y = 0; y < chBox.length; y++) {
var stringConcat = "/\b" + chBox[x] + ",?\b/";
var patt = new RegExp(eval(stringConcat));
console.log("value to check: " + chBox[y] + " " + values + " index " + patt.test(values));
but I can't get it to work. if I change it to this
var patt = new RegExp(/\b17,?\b/)
and then run
patt.test(values)
it works fine.
I'm passing in
var checkbox = ["17", "23"];
Can anyone tell me where I am going wrong
thanks
the code that works
for (var y = 0; y < chBox.length; y++) {
var stringConcat = "\\b" + chBox[y] + ",?\\b";
var patt = new RegExp(stringConcat);
if (patt.test(values) == false) return false;
}
There's no need for eval as its already a string. Just pass that to the RegExp constructor. You should also drop the leading and trailing / as that will be interpreted as part of the expression.
Related
I have this array of objects here that I am traversing and want to display a match if the person at the current index has an age within +/- 10 years of anyone else in the array. However, when I run it, it says "Cannot read property 'age' of undefined." Where did I go wrong?
function findmatches() {
var n = USERS.length;
for (var i = 0; i < n; i++) {
var currName = USERS[i].firstName;
var currAge = USERS[i].age;
var currGender = USERS[i].gender;
for (var c = 0; c < 10; c++) {
if (((USERS[c].age) + 10) <= currAge) {
document.getElementById("showmatches").innerHTML += currName + " matched to >> " + USERS[i].firstName + " " + USERS[i].lastName + " \n";
break;
}
}
}
}
What exactly is your second for loop supposed to do?
In the code you posted, it iterates through first 10 users in the USERS array. I assume it has less users than that, so at some point USERS[c] is undefined, and you're trying to access USERS[c].age.
I want to make sure that a string contains an even number of closed and open brackets.
How can I count the number of open and closed brackets of a string in JavaScript and then compare the results?
Preferable without a use of regex.
Thanks you very much in advance!
You can use String.prototype.split:
str.split("(").length === str.split(")").length
Some straightforward JavaScript:
function count_chars(s) {
var i = s.length, r = {};
while (i--) r[s[i]] = r[s[i]] ? r[s[i]]+1 : 1;
return r;
}
var str = 'ab(sdf)sdf(sdf))';
var chars = count_chars(str);
console.log('( count = ' + (chars['('] || 0));
console.log(') count = ' + (chars[')'] || 0));
console.log('{ count = ' + (chars['{'] || 0));
returns:
( count = 2
) count = 3
{ count = 0
This question already has answers here:
$().each vs $.each vs for loop in jQuery?
(3 answers)
Closed 8 years ago.
i have a doubt about the following scripts which one produce a better performance and how?
Using For Loop:
var words=$(".countryList option:selected").text().split(/ +/);
var sum=0;
var limit=14;
var appendWord="";
for(var i = 0; i < words.length; i++){
sum = sum + words[i].length;
if(sum <= limit){
appendWord = appendWord + " " + words[i];
sum = sum + 1;
}
}
Using $.each() :
var words =$(".countryList option:selected").text();
var arr = words.split(/ +/);
var textLimit=13;
var length=0;
var splittedText= '';
$.each(arr,function(i, val){
length = length + arr[i].length;
if(length <= textLimit){
splittedText = splittedText + ' ' + arr[i];
length = length + 1;
}
});
Here i get the Text from select box and tell to select box to display limited words or characters only..
Yes if we are taking about perfoemance: for loop is much faster than each .
You can verify the same using the console with date funciton that will show the curent date.
This question already has answers here:
How to replace plain URLs with links?
(25 answers)
Closed 9 years ago.
I've nearly got this working. I wanted to know if there was a much better way.
Root problem
Fiddle
function replaceURLWithHTMLLinks(text) {
text = text.replace(/a/g, "--ucsps--");
text = text.replace(/b/g, "--uspds--");
var arrRegex = [
/(\([^)]*\b)((?:https?|ftp|file):\/\/[-A-Za-z0-9+&##\/%?=~_()|!:,.;]*[-A-Za-z0-9+&##\/%=~_()|])(\))/ig,
/(\([^)]*\b)((?:https?|ftp|file):\/\/[-A-Za-z0-9+&##\/%?=~_()|!:,.;]*[-A-Za-z0-9+&##\/%=~_()|])(.?\b)/ig,
/()(\b(?:https?|ftp|file):\/\/[-a-z0-9+&##\/%?=~_()|!:,.;]*[-a-z0-9+&##\/%=~_()|])(.?\b)/ig];
for (i = 0; i < arrRegex.length; i++) {
text = text.replace(arrRegex[i], "$1a$2b$3");
}
text = text.replace(/a([^b]*)b/g, "<a href='$1'>$1</a>");
text = text.replace(/--ucsps--/g, "a");
text = text.replace(/--uspds--/g, "b");
return text;
}
var elm = document.getElementById('trythis');
elm.innerHTML = replaceURLWithHTMLLinks(elm.innerHTML);
Any thoughts?
Over at CodeReview this question was answered quite splendidly.
function replaceURLWithHTMLLinks(text) {
var re = /(\(.*?)?\b((?:https?|ftp|file):\/\/[-a-z0-9+&##\/%?=~_()|!:,.;]*[-a-z0-9+&##\/%=~_()|])/ig;
return text.replace(re, function(match, lParens, url) {
var rParens = '';
lParens = lParens || '';
// Try to strip the same number of right parens from url
// as there are left parens. Here, lParenCounter must be
// a RegExp object. You cannot use a literal
// while (/\(/g.exec(lParens)) { ... }
// because an object is needed to store the lastIndex state.
var lParenCounter = /\(/g;
while (lParenCounter.exec(lParens)) {
var m;
// We want m[1] to be greedy, unless a period precedes the
// right parenthesis. These tests cannot be simplified as
// /(.*)(\.?\).*)/.exec(url)
// because if (.*) is greedy then \.? never gets a chance.
if (m = /(.*)(\.\).*)/.exec(url) ||
/(.*)(\).*)/.exec(url)) {
url = m[1];
rParens = m[2] + rParens;
}
}
return lParens + "<a href='" + url + "'>" + url + "</a>" + rParens;
});
}
Note: I had errors with the "#" symbol in the "var re" - I just replaced it with ##
Guess this question is already answered here
function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Unique ID that gets a date in specific format?
(2 answers)
Closed 8 years ago.
I have a generate id button, when I click on the button it generates the date '2013-06-13' in a textbox. I want to add a 4 digit counter to the end of it so it will look like this '2013-06-13-xxxx' (0001, 0002, etc). When I click on the the generate button I want it to show '2013-06-13-0001' then I will push a submit button and the form will reset. When I push the generate id button again I want it to show '2013-06-13-0002' what code may I use to do this?
var counter = 0000;
function Counter() {
if((document.getElementById("generateid").clicked == true)
{
Counter++
return counter;
}
}
This is the output code
function guidGenerator() {
var theID = (Year() + "-" + Month() + "-" + Day() + "-" + Counter);
return theID;
}
You can use this:
var str = '000' + Counter();
var result = str.substring(str.length - 4);
var theID = (Year() + "-" + Month() + "-" + Day() + "-" + result);
I think here is what you looking for How to output integers with leading zeros in JavaScript
like this function below
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length-size);
}
and actually you just need s = "000" + num;