I'm trying to match a specific URL(http://www.example.me/area/?si=) that allows me to get value from si. si value will be dynamic
http://www.example.me/area/?si=4077765
Get any query string value
function qstr(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return false;
}
Check Query String Exists
function isset_qstr(field) {
var url = vp_furl();
if (url.indexOf('?' + field + '=') != -1) {
return true;
} else if (url.indexOf('&' + field + '=') != -1) {
return true;
}
return false;
}
I think you need the first function. Vote up if you think its helpful.
Thank you. Good Luck
Assuming that the value of the si key in the query string will always be digits (ie: 0 - 9), try this...
var url = 'http://www.example.me/area/?test=4894&si=4077765&f=fjjjf',
si = url.match(/.*[\?&]si=(\d+)/i)[1];
or a little more generic...
function getQueryStringValue(url, key) {
var regex = new RegExp('.*[\\?&]' + key + '=(\\d+)', 'i');
return url.match(regex)[1];
}
if not digits try this...
/.*[\?&]si=(\w+)/i
Explanation:
.* matches any character (except newline) between 0 and unlimited times
[\?&] match a single character, either ? or &
si= matches the characters si= literally (case insensitive)
(\d+) first capturing group. matches any digit [0-9] between 1 and unlimitted times
i modifier - case insensitive
regex101
Something like that can do the trick I think:
var regex = /http\:\/\/www\.example\.me\/area\/\?si=(\w*)/;
var url = 'http://www.example.me/area/?si=4077765';
var si = url.match(regex)[1]; // si = '4077765'
The first part of the regex is simply your URL "\" is used to escape special characters.
(\d+) is a capturing group that matches all character from a-z, A-Z, 0-9, including the _ (underscore) character from 0 to n iteration.
I am working on a JavaScript code that will decompose a RegExp into its base components and give a small explanation as to what it does.
My general idea is to split the input string (as a RegExp) into entries from another array.
My current code:
function interpret(regex){
var r = regex + "";
r = r.split("/");
body = r[1];
flags = r[2];
var classes = [".","\w","\d","\s","\W","\D","\S","[","]"];
var classdefs = ["any non-newline character","any word (digit or letter)","any digit (characters 0-9)","any whitespace character","any non-word (non-digit and non-letter)","any non-digit (not characters 0-9)","open matchset","close matchset"];
var quantifiers = ["*","+","?",
/{(\d+)}/g, // a{n}
/{(\d+),}/g, // a{n,}
/{(\d+),(\d+)}/g, // a{n,m}
/[+*?]\?/g // a<quant>? - lazy quantification
];
var quantDefs = ["repeated 0 or more times","repeated 1 or more times","repeated once or not at all","repeated exactly $1 time","repeated $1 or more times","repeated between $1 and $2 times"];
var escaped = ["\t","\n","\r","\.","\*","\\","\^","\?","\|"];
var escapedDefs = ["a tab","a linefeed","a carriage return","a period","an asterisk","a backslash","a carot","a question mark","a vertical bar"];
// code to split r based on entries in classes, quantifiers, and escaped.
}
Ideally, this function (lets call it splitR) will return outputs something like this:
> splitR("hello",["he","l"]);
["he", "l", "l", "o"]
> splitR("hello",["he"]);
["he", "llo"]
> splitR("hello",["he","o"]);
["he", "ll", "o"];
> splitR("5 is the square root of 25",[/\d+/g,/\w{3,}/g,"of"]);
["5", " is ", "the", " ", "square", " ", "root", " ", "of", " ", "25"]
Clearly defined, the splitR function should, in the context of the interpret function, take a RegExp and split it into its base components; e.g. \d+[0-9]\w*? should split into ["\d", "+", "[", "0-9", "]", "\w", "*", "?"]. These components are defined separately in other arrays, using a variety of RegExps (e.g. /{(\d+)}/g to find a{n}) and strings (e.g. ".").
Truly, I am stumped as to the definition of splitR. Any help is appreciated!
This will split a regex in parts, and populate a second array with description of the parts. It will skip unexpected characters, but there's no real regex syntax checking, i.e. if you start a range and don't end it, the script will not complain. I took the liberty of adding some things that were missing from your lists, like grouping brackets, start and end anchors...
function interpret(regex)
{
var body = regex.source;
var flags = (regex.global ? "g" : "") + (regex.ignoreCase ? "i" : "") + (regex.multiline ? "m" : "");
var classes = [/^\w\-\w/,/^\./,/^\\w/,/^\\d/,/^\\s/,/^\\W/,/^\\D/,/^\\S/,/^\[/,/^\]/,/^\(/,/^\)/,/^\^/,/^\$/,/^\|/];
var classDefs = ["character range","any non-newline character","any word (digit or letter)","any digit (characters 0-9)","any whitespace character","any non-word (non-digit and non-letter)","any non-digit (not characters 0-9)","any non-whitespace character","open matchset","close matchset","open group","close group","start anchor or negation","end anchor","alternative"];
var quantifiers = [/^[+*?]\?/,/^\*/,/^\+/,/^\?/,/^{(\d+)}/,/^{(\d+),}/,/^{(\d+),(\d+)}/];
var quantDefs = ["lazy quantification","repeated 0 or more times","repeated 1 or more times","repeated once or not at all","repeated exactly $1 time","repeated $1 or more times","repeated between $1 and $2 times"];
var escaped = [/^\\t/,/^\\n/,/^\\r/,/^\\\./,/^\\\*/,/^\\\+/,/^\\\-/,/^\\\\/,/^\\\^/,/^\\\$/,/^\\\?/,/^\\\|/,/^\\\[/,/^\\\]/,/^\\\(/,/^\\\)/,/^\\\{/,/^\\\}/];
var escapedDefs = ["a tab","a linefeed","a carriage return","a period","an asterisk","a plus","a minus","a backslash","a caret","a dollar sign","a question mark","a vertical bar","a square bracket","a square bracket","a bracket","a bracket","a curly bracket","a curly bracket"];
var literal = [/^[^\.\\\[\]\(\)\^\$\|\*\+\-\?\{\}]+/];
var literalDefs = ["literal text"];
var regs = classes.concat(quantifiers,escaped,literal);
var defs = classDefs.concat(quantDefs,escapedDefs,literalDefs);
var reglist = [];
var deflist = [];
while (body.length)
{
var found = false;
var chunk = null;
for (var i = 0; i < regs.length; i++)
{
chunk = body.match(regs[i]);
if (chunk)
{
reglist.push(chunk[0]);
deflist.push(defs[i]);
body = body.substr(chunk[0].length);
found = true;
break;
}
}
if (!found)
{
body = body.substr(1); // skip unexpected character
}
}
console.log(regex.source);
console.log(reglist);
console.log(deflist);
alert("see console for output");
}
var x = new RegExp("^[a-z0-9]\\^.\\.\\w\\d\\s\\W\\D\\S+(te|\\|st)*\\*\\n+\\+\\-\\}(\\W?\\?\\s{1,3})\\\\*?a{3}b{4,}c{}\\r\\t\\$$", "ig");
interpret(x);
Assume that there is a string like this:
var content = "1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20";
I want to add <br /> after every 5 dots.
So, the result should be:
1.2.3.4.5.<br />
6.7.8.9.10.<br />
11.12.13.14.15.<br />
16.17.18.19.20.<br />
I want to do this without a for loop. Is it possible with just regex?
i'm doing this with this code;
regenerate:function(content,call){
var data2;
var brbr = content.replace(/[\u0250-\ue007]/g, '').match(/(\r\n)/g);
if (brbr !== "") {
data2 = content.replace(/[\u0250-\ue007]/g, '').replace(/(\r\n)/gm, "<br><br>");
} else {
data2 = content.replace(/[\u0250-\ue007]/g, '');
}
var dataArr = data2.split(".");
for (var y = 10; y < dataArr.length - 10; y += 10) {
var dataArrSpecific1 = dataArr[y] + ".";
var dataArrSpecific2 = dataArr[y] + ".<br>";
var dataArrSpecificBosluk = dataArr[y + 1];
var data3 = data2.replace(new RegExp(dataArrSpecific1.replace(/[\u0250-\ue007]/g, ''), "g"), "" + dataArrSpecific2.replace(/[\u0250-\ue007]/g, '') + "");
data3 = data3.replace(new RegExp(dataArrSpecificBosluk.replace(/[\u0250-\ue007]/g, ''), "g"), " " + dataArrSpecificBosluk.replace(/[\u0250-\ue007]/g, '') + "");
data2 = data3;
}
call(data2.replace(/[\u0250-\ue007]/g, ''));
}
Actually , i want to refactoring this code
Working bin:http://jsbin.com/dikifipelo/1/
var string = "1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20." ;
string = string.replace(/(([^\.]+\.){5})/g, "$1<br/>");
Works with any type and length of characters between the dots.
Explanation:
The pattern /(([^.]+.){5})/g can be broken down as such:
[^\.] - any character that is not a dot
[^\.]+ - any character that is not a dot, one or more times
[^\.]+\. - any character that is not a dot, one or more times, followed by a dot
([^\.]+\.){5} - any character....dot, appearing five times
(([^\.]+\.){5}) - any...five times, capture this (all round brackets capture unless told not to, with a ?: as the first thing inside them)
the /g/ flag makes it so that the whole string is matched - ie, all matches are found
"$1" represents the results of the first group (or bracket)
so, the replace function finds all instances of the pattern in the string, and replaces them with the match itself + a line break (br).
Once you learn regular expressions, life is never the same.
What is the best way to count how many spaces before the fist character of a string?
str0 = 'nospaces even with other spaces still bring back zero';
str1 = ' onespace do not care about other spaces';
str2 = ' twospaces';
Use String.prototype.search
' foo'.search(/\S/); // 4, index of first non whitespace char
EDIT:
You can search for "Non whitespace characters, OR end of input" to avoid checking for -1.
' '.search(/\S|$/)
Using the following regex:
/^\s*/
in String.prototype.match() will result in an array with a single item, the length of which will tell you how many whitespace chars there were at the start of the string.
pttrn = /^\s*/;
str0 = 'nospaces';
len0 = str0.match(pttrn)[0].length;
str1 = ' onespace do not care about other spaces';
len1 = str1.match(pttrn)[0].length;
str2 = ' twospaces';
len2 = str2.match(pttrn)[0].length;
Remember that this will also match tab chars, each of which will count as one.
You could use trimLeft() as follows
myString.length - myString.trimLeft().length
Proof it works:
let myString = ' hello there '
let spacesAtStart = myString.length - myString.trimLeft().length
console.log(spacesAtStart)
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/TrimLeft
str0 = 'nospaces';
str1 = ' onespace do not care about other spaces';
str2 = ' twospaces';
arr_str0 = str0.match(/^[\s]*/g);
count1 = arr_str0[0].length;
console.log(count1);
arr_str1 = str1.match(/^[\s]*/g);
count2 = arr_str1[0].length;
console.log(count2);
arr_str2 = str2.match(/^[\s]*/g);
count3 = arr_str2[0].length;
console.log(count3);
Here:
I have used regular expression to count the number of spaces before the fist character of a string.
^ : start of string.
\s : for space
[ : beginning of character group
] : end of character group
str.match(/^\s*/)[0].length
str is the string.
I have this string :
var a='abc123#xyz123';
I want to build 2 regexes replace functions which :
1) Replace all characters that do have a future '#' - with '*' (not including '#')
so the result should look like :
'******#xyz123'
2) Replace all characters that do not have a future '#' - with '*' (not including '#')
so the result should look like :
'abc123#******'
What have I tried :
For the positive lookahead :
var a='abc123#xyz123';
alert(a.replace(/(.+(?=#))+/ig,'*')); //*#xyz123 --wrong result since it is greedy...
Question :
How can I make my regexes work as expected ?
First part using lookahead:
repl = a.replace(/.(?=[^#]*#)/g, "*");
//=> "******#xyz123"
Explanation:
This regex finds any character that is followed by # using lookahead and replaced that with *.
Second part using replace callback:
repla = a.replace(/#(.*)$/, function(m, t) { return m[0] + t.replace(/./g, '*'); } );
//=> abc123#******
Explanation:
This code finds text after #. Inside the callback function is replaces every character with asterisk.
You can use indexOf and substr for this instead:
function maskBeforeAfter(before, str, character, maskCharacter) {
character = character || '#';
maskCharacter = maskCharacter || '*';
var characterPosition = str.indexOf(character);
if (characterPosition > -1) {
var mask = '';
if (before) {
for (var i = 0; i < characterPosition; i++) {
mask += maskCharacter;
}
return mask + str.substr(characterPosition);
} else {
for (var i = 0; i < str.length - characterPosition - 1; i++) {
mask += maskCharacter;
}
return str.substr(0, characterPosition + 1) + mask;
}
}
return str;
}
function maskBefore(str, character, maskCharacter) {
return maskBeforeAfter(true, str, character, maskCharacter);
}
function maskAfter(str, character, maskCharacter) {
return maskBeforeAfter(false, str, character, maskCharacter);
}
> var a = 'abc12345#xyz123';
> maskBefore(a);
"********#xyz123"
> maskAfter(a);
"abc12345#******"
If you insist on a simple regex:
The first one is already answered. The second can be written similarly:
a.replace(/[^#](?![^#]*#)/g, '*')
(?![^#]*#) is a negative lookahead that checks that there isn't a pound after the current character.
[^#] also checks that the current character isn't a pound. (we could have also used /(?![^#]*#)./g, but it is less pretty.
A positive option is:
a.replace(/[^#](?=[^#]*$)/g, '*');
this is very similar to the first one: (?=[^#]*$) checks that we have only non-pounds ahead, until the end of the string.
In both of this options, all characters in strings with no pounds will be replaces: "abcd" -> "****"