Regular Expressions required format - javascript

I want to validate following text using regular expressions
integer(1..any)/'fs' or 'sf'/ + or - /integer(1..any)/(h) or (m) or (d)
samples :
1) 8fs+60h
2) 10sf-30m
3) 2fs+3h
3) 15sf-20m
i tried with this
function checkRegx(str,id){
var arr = strSplit(str);
var regx_FS =/\wFS\w|\d{0,9}\d[hmd]/gi;
for (var i in arr){
var str_ = arr[i];
console.log(str_);
var is_ok = str_.match(regx_FS);
var err_pos = str_.search(regx_FS);
if(is_ok){
console.log(' ID from ok ' + id);
$('#'+id).text('Format Error');
break;
}else{
console.log(' ID from fail ' + id);
$('#'+id).text('');
}
}
}
but it is not working
please can any one help me to make this correct

This should do it:
/^[1-9]\d*(?:fs|sf)[-+][1-9]\d*[hmd]$/i
You were close, but you seem to be missing some basic regex comprehension.
First of all, the ^ and $ just make sure you're matching the entire string. Otherwise any junk before or after will count as valid.
The formation [1-9]\d* allows for any integer from 1 upwards (and any number of digits long).
(?:fs|sf) is an alternation (the ?: is to make the group non-capturing) to allow for both options.
[-+] and [hmd] are character classes allowing to match any one of the characters in there.
That final i allows the letters to be lowercase or uppercase.

I don't see how the expression you tried relates anyhow to the description you gave us. What you want is
/\d+(fs|sf)[+-]\d+[hmd]/
Since you seem to know a bit about regular expressions I won't give a step-by-step explanation :-)
If you need exclude zero from the "integer" matches, use [1-9]\d* instead. Not sure whether by "(1..any)" you meant the number of digits or the number itself.
Looking on the code, you
should not use for in enumerations on arrays
will need string start and end anchors to check whether _str exactly matches the regex (instead of only some part)
don't need the global flag on the regex
rather might use the RegExp test method than match - you don't need a result string but only whether it did match or not
are not using the err_pos variable anywhere, and it hardly will work with search
function checkRegx(str, id) {
var arr = strSplit(str);
var regx_FS = /^\d+(fs|sf)[+-]\d+[hmd]$/i;
for (var i=0; i<arr.length; i++) {
var str = arr[i];
console.log(str);
if (regx_FS.test(str) {
console.log(' ID from ok ' + id);
$('#'+id).text('Format Error');
break;
} else {
console.log(' ID from fail ' + id);
$('#'+id).text('');
}
}
}
Btw, it would be better to separate the validation (regex, array split, iteration) from the output (id, jQuery, logs) into two functions.

Try something like this:
/^\d+(?:fs|sf)[-+]\d+[hmd]$/i

Related

Check for existence of a keyword within a code string

I’m loading the contents of a JS file using FileReader and dumping the results into a textarea container. I then want to run some checks on the actual JS file.
I know there are probably tools out there for this already (or better ways), but this is for a closed-environment project.
After the textarea contains the content of the JS file as one large string, I need to loop the string and find all instances of parseInt() to check if they have been supplied with a radix.
I would provide code, but I have nothing working at this point. Any ideas?
The following snippet will search the string value of your <textarea> element for parseInt() and output the occurences, with radix where applicable:
var textareaValue = 'var func = function(){' +
'var i = parseInt(1,1);' +
'var j = parseInt(10, 10);' +
'var k = parseInt(3) + j;' +
'};';
occurences = textareaValue.match(/parseInt\(.+?(, ?\d+)?\)/g);
occurences.forEach(function(occurence){
var hasRadix = /, ?\d+\)$/.test(occurence);
document.body.innerHTML += '<p>"' + occurence + '" has ' +
(hasRadix ? 'a' : 'no') + ' radix' +
(hasRadix ? ' (' + occurence.match(/, ?(\d+)\)$/)[1] + ')' : '') +
'.</p>';
});
Note that this is no actual syntax interpretation, it’s merely text analysis. You will have to go from the result, which comprises all the occurences of parseInt() as strings. Also, JavaScript allows whitespace, comments, expressions and other witchcraft at the text passage in question. You might to have to check for anything.
The actual regex /parseInt\(.+?(, ?\d+)?\)/g will demand…
parseInt( at the beginning of the match
any characters (might need to be expanded to include brackets, etc. by :punct:)
as optional group, determining whether a radix is supplied or not:
a comma, an optional space (might need to respond to any number of whitespace using *)
at least one digit (might need to limit to {1,2}, because only 2 to 36 are valid)
a trailing closing bracket.
The following function should be able to tell the difference between usages of parseInt with radix versus its usages without radix by simplistic regex matching:
function have_radix(str){
parseIntRegex = /parseInt\(.+?\)/g;
parseIntRegexWithRadix = /parseInt\(.+?(,.+?\))/g;
indices = [];
while ( (result = parseIntRegex.exec(str)) ) {
indices.push(result.index);
}
count = indices.length;
indices = [];
while ( (result = parseIntRegexWithRadix.exec(str)) ) {
indices.push(result.index);
}
diff = count - indices.length;
return diff;
}

Javascript search string for numbers regex maybe?

I have a string like
:21::22::24::99:
And I want to find say if :22: is in said string. But is there a means of searching a string like above for one like I want to match it to with javascript, and if there is, does it involve regex magic or is there something else? Either way not sure how to do it, more so if regex is involved.
You can build the regular expression you need:
function findNumberInString(num, s) {
var re = new RegExp(':' + num + ':');
return re.test(s);
}
var s = ':21::22::24::99';
var n = '22';
findNumberInString(n, s); // true
or just use match (though test is cleaner to me)
!!s.match(':' + n + ':'); // true
Edit
Both the above use regular expressions, so a decimal ponit (.) will come to represent any character, so "4.1" will match "461" or even "4z1", so better to use a method based on String.prototype.indexOf just in case (unless you want "." to represent any character), so per Blender's comment:
function findNumberInString(num, s) {
return s.indexOf(':' + num + ':') != -1;
}
like this:
aStr = ':21::22::24::99:';
if(aStr.indexOf(':22:') != -1){
//':22:' exists in aStr
}
else{
//it doesn't
}

Convert slug variable to title text with javascript

I'm trying to do something that would be similar to turning a url slug-like variable into text that could be used for a title.
So, I have a variable for example that is like this:
var thisID = 'athlete-profile';
function myFunc(thisID) {
// i need to use thisID as the id and href in a loop that generates a string of <li><a>'s\
function makeTitle(thisID) {
// convert thisID to text so for this example it would return 'Athlete Profile'
return 'Athlete Profile';
}
for () {
var str = '<li id="'+thisID+'">'+makeTitle(thisID)+'';
}
// make sense?
}
I'd like to not use a regex to do this if possible somehow, but I don't think there's a way to do it without one. So any one who knows how to do this type of thing let me know, it would be a great help.
Thanks
I would advise you to use regular expression. But if you really don't want to use regular expressions, the solution below would work for simple cases. Feel free to modify it as you like it.
function makeTitle(slug) {
var words = slug.split('-');
for (var i = 0; i < words.length; i++) {
var word = words[i];
words[i] = word.charAt(0).toUpperCase() + word.slice(1);
}
return words.join(' ');
}
console.log(
makeTitle("athlete-profile")
)
function titleize(slug) {
var words = slug.split("-");
return words.map(function(word) {
return word.charAt(0).toUpperCase() + word.substring(1).toLowerCase();
}).join(' ');
}
console.log(titleize("athlete-profile"))
It works pretty simply:
It splits the string by - into words.
It maps each word into title case.
It joins the resulting words with spaces.
Do it in one line:
'athlete-profile'.split("-").join(" ").replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()})
Output: Athlete Profile
The makeTitle() part of your question can be implemented something like this:
function makeTitle(thisID) {
return thisID.replace(/-/g, " ").replace(/\b[a-z]/g, function() {
return arguments[0].toUpperCase();
});
}
console.log(makeTitle("athlete-profile"))
The first .replace() changes all hyphens to spaces, and then the second .replace() takes any lower-case letter that follows a word boundary and makes it upper-case.
(For more information see the MDN doco for .replace().)
As far as doing it without using regular expressions, I'm not sure why you'd specifically want to avoid them, especially when the required expressions are pretty simple in this case (especially if you do the hyphen to space and first letter capitalisation in two steps as shown above). But there are endless ways to do this without regex using various combinations of JavaScript's string manipulation methods.
Do it like this
let someString = 'im a string';
console.log(someString.replace(/-/g, ' ')
.replace(/\w\S*/g, function (txt) {
return
txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()
})
)
Output: Im A String
Short and great way:
const slugToText = (slug) => {
return slug.toLowerCase().replace(/-/g,' ')
}
Much Simplified answer
we can use String.prototype.replaceAll method to easily achieve this
function convertSlugToString(slug) {
return slug.replaceAll("-", " ");
}
incase you want to make sure the output is all lowercase then you can do the following
function convertSlugToString(slug) {
return slug.toLowerCase().replaceAll("-", " ");
}
Additional info:
String.prototype.replaceAll() is a ES2021 feature and it also has a great browser support with 93.64% global coverage, click here for more info
if you want to support IE then refer to the other answers

Regex, grab only one instance of each letter

I have a paragraph that's broken up into an array, split at the periods. I'd like to perform a regex on index[i], replacing it's contents with one instance of each letter that index[i]'s string value has.
So; index[i]:"This is a sentence" would return --> index[i]:"thisaenc"
I read this thread. But i'm not sure if that's what i'm looking for.
Not sure how to do this in regex, but here's a very simple function to do it without using regex:
function charsInString(input) {
var output='';
for(var pos=0; pos<input.length; pos++) {
char=input.charAt(pos).toLowerCase();
if(output.indexOf(char) == -1 && char != ' ') {output+=char;}
}
return output;
}
alert(charsInString('This is a sentence'));
As I'm pretty sure what you need cannot be achieved using a single regular expression, I offer a more general solution:
// collapseSentences(ary) will collapse each sentence in ary
// into a string containing its constituent chars
// #param {Array} the array of strings to collapse
// #return {Array} the collapsed sentences
function collapseSentences(ary){
var result=[];
ary.forEach(function(line){
var tmp={};
line.toLowerCase().split('').forEach(function(c){
if(c >= 'a' && c <= 'z') {
tmp[c]++;
}
});
result.push(Object.keys(tmp).join(''));
});
return result;
}
which should do what you want except that the order of characters in each sentence cannot be guaranteed to be preserved, though in most cases it is.
Given:
var index=['This is a sentence','This is a test','this is another test'],
result=collapseSentences(index);
result contains:
["thisaenc","thisae", "thisanoer"]
(\w)(?<!.*?\1)
This yields a match for each of the right characters, but as if you were reading right-to-left instead.
This finds a word character, then looks ahead for the character just matched.
Nevermind, i managed:
justC = "";
if (color[i+1].match(/A/g)) {justC += " L_A";}
if (color[i+1].match(/B/g)) {justC += " L_B";}
if (color[i+1].match(/C/g)) {justC += " L_C";}
if (color[i+1].match(/D/g)) {justC += " L_D";}
if (color[i+1].match(/E/g)) {justC += " L_E";}
else {color[i+1] = "L_F";}
It's not exactly what my question may have lead to belive is what i wanted, but the printout for this is what i was after, for use in a class: <span class="L_A L_C L_E"></span>
How about:
var re = /(.)((.*?)\1)/g;
var str = 'This is a sentence';
x = str.toLowerCase();
x = x.replace(/ /g, '');
while(x.match(re)) {
x=x.replace(re, '$1$3');
}
I don't think this can be done in one fell regex swoop. You are going to need to use a loop.
While my example was not written in your language of choice, it doesn't seem to use any regex features not present in javascript.
perl -e '$foo="This is a sentence"; while ($foo =~ s/((.).*?)\2/$1/ig) { print "<$1><$2><$foo>\n"; } print "$foo\n";'
Producing:
This aenc

Why does this jQuery code not work?

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

Categories