Regex Javascript use variable within pattern - javascript

I know that this's been asked before but none of the suggested solutions worked for me. I've got the following:
var regex = new RegExp(/D0030001 IN/gi);
$("p").filter(function () {
return regex.test(this.id);
}).css("background-color","blue");
This one works fine. However, when I try to do
spl = [];
spl[0] = "D0030001";
spl[1] = "IN";
var regex = new RegExp("/" + spl[0] + " " + spl[1] + "/gi");
$("p").filter(function () {
return regex.test(this.id);
}).css("background-color","blue");
This one doesn't work. In other words I need to use variables to construct the regex pattern. Thanks

You need to use the second argument of RegExp constructor to set the flags and you don't need / / delimiters.
var regex = new RegExp(spl[0] + " " + spl[1], "gi");

Related

Regex for URL/String - If protocol return false

Trying to create a regex in which the string should not start with http(s)://, http(s)://www. Rest of the string can be anything.
I used this regeg but its return true if we have http://
^(http://www.|https://www.|http://|https://)?[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(:[0-9]{1,5})?(/.*)?$
Another one I tried is
var re = new RegExp("(http|https|ftp)://");
var str = "http://xxxx.com";
var match = re.test(str);
console.log(match);
this one is also returning true.
Demo here
let re = /(http|https|ftp):///;
let url = 'xxxx.xxxx.xxxx'; // this is valid but test returns false
let url2 = 'https://www.xxzx.com/xxx.aspx'; // this should fail as there is https://www in url
console.log(re.test(url)); //
console.log(re.test(url2)); //
Is this possible with regex?
You need to use negative lookahead in your regex to discard strings starting with protocols like http or https or ftp. You can use this regex,
^(?!(?:ftp|https?):\/\/(www\.)?).+$
Regex Demo
JS Demo,
const arr = ['xxxx.xxxx.xxxx','ftp://www.xxzx.com/xxx.aspx','https://www.xxzx.com/xxx.aspx','http://xxxx.com','https://xxzx.com/xxx.aspx','http://www.xxxx.com']
arr.forEach(s => console.log(s + " --> " + /^(?!(?:ftp|https?):\/\/(www\.)?).+$/.test(s)))
It's probably possible to do with regexes, but unless you have to use a regex, you should use the URL class:
let HTTP_URL = 'https://www.xxzx.com/xxx.aspx'
let HTTPS_URL = 'https://www.xxzx.com/xxx.aspx'
let FTP_URL = 'ftp://www.xxzx.com/xxx.aspx'
let GOOD_PROTOCOL = 'mysql://www.xxzx.com/xxx.aspx'
let GOOD_INPUT = '129.123.12.123'
function test_url(url) {
let bad_protocols = ['http:', 'https:', 'ftp:']
try {
var parsed = new URL(url)
} catch {
return true
}
return (!bad_protocols.contains(parsed.protocol))
}
test_url(HTTP_URL) //false
test_url(HTTPS_URL) //false
test_url(FTP_URL) //false
test_url(GOOD_PROTOCOL) //true
test_url(GOOD_INPUT) //true
If you're just trying to negate that regex:
function doesMatch(string) {
return !/^http(s):\/\/(?:www)?/.test(string);
}
[
'https://www.xxzx.com/xxx.aspx',
'http://www.xxxx.com',
'https://xxxx.com',
'http://xxxx.com',
'https://aaaa.com',
'aaaa.com'
].forEach(s => console.log(doesMatch(s)));
In your example code, re.test(url) returns false , because there is no presence of http or https in that string.
In url2 (ie..'https://www.xxzx.com/xxx.aspx') , there is a presence of https so it is returning true.
This expression might also work, it would allow your desired input and fails all other URLs, and you can also simply add to its char list, what else might be undesired to start:
^([^http|s|ftp|www|\/\/|])*
Pass
xxxx.xxxx.xxxx
Fail
ftp://www.xxzx.com/xxx.aspx
https://www.xxzx.com/xxx.aspx
http://xxxx.com
https://xxzx.com/xxx.aspx
http://www.xxxx.com
//www.xxxx.com
You can test/modify/change it in this link.
RegEx Descriptive Graph
This graph shows how the expression would work and you can visualize other expressions in this link:
Performance Test
This JavaScript snippet shows the performance of that expression using a simple 1-million times for loop.
const repeat = 1000000;
const start = Date.now();
for (var i = repeat; i >= 0; i--) {
const string = 'xxxx.xxxx.xxxx';
const regex = /(^([^http|s|ftp|www|\/\/|])*)/gm;
var match = string.replace(regex, "$1");
}
const end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match 💚💚💚 ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");

Adding quotes to a comma separated string

What I have:
var a = "1.1.1.1,2.2.2.2,3.3.3.3"
What I need:
var a = '1.1.1.1','2.2.2.2','3.3.3.3'
What I'm trying:
var a = "1.1.1.1,2.2.2.2,3.3.3.3"
var b = a.split(",")
var c
for (var i=0;i<b.length; i++)
{
c.concat("\'").concat(b[i]).concat("\',\"")
}
What I'm actually getting with the above
"'1.1.1.1','"
I'm only able to get the first element right, how do I rectify this?
Also, in JS, is it even possible to have something like '1.1.1.1','2.2.2.2','3.3.3.3' stored in a variable?
A background to this problem:
I have an iframe whose source is a kibana query. The query in fact takes in values to a particular parameter in the above mentioned format.
Eg:
params:!('1.1.1.1','2.2.2.2')
While my db contains the param values as a string of CSV.
Eg.
"1.1.1.1,2.2.2.2,3.3.3.3"
Try this
var a = "1.1.1.1,2.2.2.2,3.3.3.3";
var b = "'" + a.split( "," ).join( "','" ) + "'";
console.log( b );
You don't need to deal with iterations for this, use a RegExp replace:
var a = "1.1.1.1,2.2.2.2,3.3.3.3";
var b = "'" + a.replace(/,/g, "','") + "'";
console.log( b );
The naive solution to your problem looks like this:
> line = '1.1.1.1,2.2.2.2,3.3.3.3'
'1.1.1.1,2.2.2.2,3.3.3.3'
> '"' + line.replace(/,/g, '","') + '"'
'"1.1.1.1","2.2.2.2","3.3.3.3"'
or if the quotes need to be reversed:
> "'" + line.replace(/,/g, "','") + "'"
'\'1.1.1.1\',\'2.2.2.2\',\'3.3.3.3\''
However, it sounds like what you need is a full-blown CSV parser, to handle cases in which you have quotes and commas and new lines and other crazy characters embedded in your input.
The naive solution seems to be in line, though, with what you were trying to do, and might illustrate why your approach fell short.
Your code works as you intended. Can you append to c without declaring?
var a = "1.1.1.1,2.2.2.2,3.3.3.3"
var b = a.split(",")
var c = ""
for (var i=0;i<b.length; b++)
{
c.concat("\'").concat(b[i]).concat("\',\"")
console.log(b)
}
You can store several values in a variables by using array for example.
If you want to get string like '"1.1.1.1","2.2.2.2","3.3.3.3"' you can use the following code:
var a = "1.1.1.1,2.2.2.2,3.3.3.3";
var b = a.split(',').map(function (str) {
return '"' + str+ '"';
}).join(',');
console.log(b);

Javascript:How to remove occurrence of a character from a value?

Here i am trying to replace an occurrence of a string and 4 characters after that by blank.
For Eg i have the below string:
var a=ssss~ABC*bvbfg~JJJ*ertert~PMU*trert~GFRG*qqqq~HGHGHG
I get the value as bvbfg
Now when i get the value i should replace bvbfg~JJJ to blank value and the string should become
var a=ssss~ABC*ertert~PMU*trert~GFRG*qqqq~hghgh
Similarly if i get the value as qqqq i should replace qqqq~HGHGHG to blank value
and the new value should be
var a=ssss~ABC*bvbfg~JJJ*ertert~PMU*trert~GFRG
I tried making using of regular expression:
Something as below(For Eg)
mystring.replace(/bvbfg/g , "newchar");
But the results i saw were not good. It is a bit tricky. Any guidance. Thanks.
function remove(str, tok) {
var regex = new RegExp('\\b' + tok + '~[^*]*\\*?', 'i'); // if you want it to be case sensetive, then remove the 'i' parameter
return str.replace(regex, '')
/*.replace(/^\*|\*$/, '')*/; // uncomment this to remove *s from the start and the end
}
var a = "ssss~ABC*bvbfg~JJJ*ertert~PMU*trert~GFRG*qqqq~HGHGHG";
console.log(remove(a, "ertert"));
Parse:
function parse(str) {
return str.split('*')
.reduce(function(res, e) {
var parts = e.split('~');
res[parts[0]] = parts[1];
return res;
}, {});
}
var a = "ssss~ABC*bvbfg~JJJ*ertert~PMU*trert~GFRG*qqqq~HGHGHG";
console.log(parse(a));
I am new to regex, this is what I tried and it seems to work.
/bvbfg~(\w+)[*]?/g
Demo: http://regexr.com/3fagf
But I would suggest you to use Wiktor Stribiżew's answer.
Here you go... short and simple :)
document.getElementById('btn').onclick = function() {
var value = document.getElementById('value').value,
a = 'ssss~ABC*bvbfg~JJJ*ertert~PMU*trert~GFRG*qqqq~HGHGHG',
regx = new RegExp('\\*?' + value + '~\\w*', 'g');
console.log(a.replace(regx, ''));
}
<input id="value" type="text">
<button id="btn">Submit</button>
Putting everything together with Stribiżew's regex:
function getRegexp(s) {
return new RegExp( s + '~[^*]*\\*?', 'gi');
}
var str = 'ssss~ABC*bvbfg~JJJ*ertert~PMU*trert~GFRG*qqqq~HGHGHG';
var s = 'bvbfg';
console.log(str.replace(getRegexp(s), ''));
s = 'qqqq';
console.log(str.replace(getRegexp(s), ''));

buillding regex expression

i want to replace specific amount of white-spaces from a String at the beginning and i can use
replace(/^\s{2}/g,"");
and it works .but 2 should be changed according to a value of a variable .so i need to construct a new RegExp()
so i used
var lead=2;
var regex = new RegExp("\^\\s{" + lead + "}//g");
alert("regex "+regex);
real output
/^\s{2}\/\/g/
expected output
/^\s{2}/g
could you help me to fix this problem.tnx
As the param to RegExp is the regex, you don't need the / delimiters. Use the flags as the second parameter to the RegEx() constructor.
var regex = new RegExp("^\\s{" + lead + "}", 'g');
Example:
var lead = 2;
var regex = new RegExp("^\\s{" + lead + "}", 'gmi');
alert(regex);
var str = ' Say My Name';
alert(str.replace(regex, ''));
new RegExp("^\\s{" + lead + "}", "g");
Try
"\^\\s{" + lead + "}\/g"
instead of
"\^\\s{" + lead + "}//g"
I think you wanted to escape the "/", but you accidently used "/" instead of "\".

Regex match not returning true or false

I am trying to match when there is a value with parenthesise.
var onsuccess = "aaa;bbb(ccc)";
onsuccess.split(';').forEach(function (success) {
var re = new RegExp("\(.*?\)");
document.write(success + ": " + success.match(re) + "<br>");
});​
Output is
aaa: ,
bbb(ccc): ,
Expected is
aaa: false
bbb(ccc): true
Where am I going wrong? I have been using this page as an example:
http://www.regular-expressions.info/javascriptexample.html
Here is my fiddle: http://jsfiddle.net/valamas/8B5zw/
thanks
var onsuccess = "aaa;bbb(ccc)";
onsuccess.split(';').forEach(function (success) {
var re = /\(.*?\)/;
document.write(success + ": " + re.test(success) + "<br>");
});
The working demo.
Note: if you using new RegExp(...), you need to escape your backslash.
You regex should be var re = new RegExp("\\(.*?\\)");, but since there is no variable in your regex, you should just use the regex literal instead.
​
.match() returns an array of matching groups.
You're thinking of .test(), which returns true or false.
Also, your \s are being swallowed by the Javascript string literal.
You should use a regex literal instead.
This was missing a group to match, and a cast to boolean:
var onsuccess = "aaa;bbb(ccc)";
onsuccess.split(';').forEach(function (success) {
//var re = new RegExp("(\(.*?\))");
var re = /.*(\(.*?\)).*/;
document.write(success + ": " + !!success.match(re) + "<br>");
});​
Use .test instead of casting
var onsuccess = "aaa;bbb(ccc)";
var rxParens = /.*(\(.*?\)).*/;
onsuccess.split(";").forEach(function(success) {
document.write(success + ': ' + rxParens.test(success) + '<br>' );
});
aaa: false
bbb(ccc): true
Just as a side note, .test performs many times faster than .match http://jsperf.com/exec-vs-match-vs-test/5

Categories

Resources