I have a requirement where there is a customet name text box and the user able to input customer name to search customer. And the condition is user can add do wild card search putting * either infront or after the customer name. And the customer name should be minimum three characters long. I am using Regex to validate the user entry.
Now in case the input is like "*aaa*" .. I am validate this type of input using the following regex :
[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}
The code is like below:
var str = "*aaa*";
var patt = new RegExp("[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}");
var res = patt.test(str);
alert(res);
var str = "*aaa***";
var patt = new RegExp("[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}");
var res = patt.test(str);
alert(res);
var str = "*aaa*$$$$";
var patt = new RegExp("[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}");
var res = patt.test(str);
alert(res);
Now for the input "*aaa*" res is coming true. But for this type of inputs also "*aaa**", "*aaa*$" its comimg true. And this expected as these expressions also contains the part( *aaa*) which satisfies the regex.But these inputs("*aaa**", *aaa*$** etc. ) are wrong.
Please let me know where I am doing wrong ? is there any issue with the regex or the way checking is wrong ?
^(?:[*]([a-z]|[A-Z]|[0-9]){3,}[*])$
Use anchors ^$ to disable partial matching.See demo.
https://regex101.com/r/tS1hW2/17
The string *aaa*$$$ contains a segment of *aaa*, so it will yield true; to match against the whole string you need to add anchors on both sides. The $ and ^ anchors assert the start and end of the subject respectively.
Also, you can simply the expression greatly by using a character class trick. The \w is comprised of [0-9a-zA-Z_], and we only don't want the underscore, so we can use a negative character class with the opposite of \w (which is \W) and an underscore; I agree, it takes some mental power ;-)
var str = "*aaa*$";
var patt = /^\*[^\W_]{3,}\*$/;
var res = patt.test(str);
alert(res); // false
Alternatively, you can merge all your character classes together into one like so:
[A-Za-z0-9]
Related
In my Javascript code, I get one very long line as a string.
This one line only has around 65'000 letters. Example:
config=123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...
What I have to do is replace all & with an break (\n) first and then pick only the line which starts with "path_of_code=". This line I have to write in a variable.
The part with replace & with an break (\n) I already get it, but the second task I didn't.
var obj = document.getElementById('div_content');
var contentJS= obj.value;
var splittedResult;
splittedResult = contentJS.replace(/&/g, '\n');
What is the fastest way to do it? Please note, the list is usually very long.
It sounds like you want to extract the text after &path_of_code= up until either the end of the string or the next &. That's easily done with a regular expression using a capture group, then using the value of that capture group:
var rex = /&path_of_code=([^&]+)/;
var match = rex.exec(theString);
if (match) {
var text = match[1];
}
Live Example:
var theString = "config=123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...";
var rex = /&path_of_code=([^&]+)/;
var match = rex.exec(theString);
if (match) {
var text = match[1];
console.log(text);
}
Use combination of String.indexOf() and String.substr()
var contentJS= "123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...";
var index = contentJS.indexOf("&path_of_code"),
substr = contentJS.substr(index+1),
res = substr.substr(0, substr.indexOf("&"));
console.log(res)
but the second task I didn't.
You can use filter() and startsWith()
splittedResult = splittedResult.filter(i => i.startsWith('path_of_code='));
I have string content that gets delivered to me via TCP. This info is only relevant because it means that I do not consistently retrieve the same string. I have a <start> and <stop> separator to ensure that any time I get the data via TCP, I am outputting the full content.
My incoming content looks like so:
<start>Apple Bandana Cadillac<stop>
I want to get everything in between <start> and <stop>. So just Apple Bandana Cadillac.
My script to do this looks like so:
servercsv.on("connection", function(socket){
let d_basic = "";
socket.on('data', function(data){
d_basic += data.toString();
let d_csvindex = d_basic.indexOf('<stop>');
while (d_csvindex > -1){
try {
let strang = d_basic.substring(0, d_csvindex);
let dyson = strang.replace(/<start>/g, '');
let dson = papaparse.parse(dyson);
myfunction(dson);
}
catch(e){ console.log(e); }
d_basic = d_basic.substring(d_csvindex+1);
d_csvindex = d_basic.indexOf('<stop>');
}
});
});
What this means is that I am getting everything before the <stop> string and outputting it. I have also included the line let dyson = strang.replace(/<start>/g, ''); because I want to remove the <start> text.
However, because this is TCP, I am not guranteed to get all parts of this string. As a result, I frequently get back stop>Apple Bandana Cadillac<stop> or some variation of this (such as start>Apple Bandana Cadillac<stop>. It is not consistent enough that I can just do strang.replace("start>", "")
Ideally, I would like my separator to select content that is in between <start> and <stop>. Not just <stop>. However, I am unsure how to do so.
Alternatively, I can also settle for a regex that retrieves all combination of <start><stop> strings during my while loop, and just delete them. So check for <, s, t, a, r, t individually and so forth. But unsure how to implement regex to delete portions of a whole string.
Assuming you get full response:
var test = "<start>Apple Bandana Cadillac<stop>";
var testRE = test.match("<start>(.*)<stop>");
testRE[1] //"Apple Bandana Cadillac"
If there are new lines between <start> and <stop>
var test = "<start>Apple Bandana Cadillac<stop>";
var testRE = test.match("<start>([\\S\\s]*)<stop>");
testRE[1] //"Apple Bandana Cadillac"
Using regular expressions capturing group here.
Try this regex with replace() method:
/<st.*?>(.*?)(?!<st)/g
Literal.................................................: <st
Any char zero or more times lazily...: .*?
Literal..................................................: >
Begin capture group..........................: (
Any char zero or more times lazily...: .*?
End capture group.............................: )
Begin negative lookahead.................: (?!
Literal...................................................: <st
End negative lookahead....................: )
In the Demo below notice that the test example consists of multiple lines, and variances of <start> and <stop> (basically <st).
Demo 1
var rgx = /<st.*?>(.*?)(?!<st)/g;
var str = `<start>Apple Bandana Cadillac<stop>
<stop>Grapes Trampoline Ham<stop>
<start>Kebab Matador Pencil<start>`;
var res = str.replace(rgx, `$1`);
console.log(res);
Update
"say I have op>Grapes Trampoline Ham<stop>...still trying to remove all parts of the string <stop>"
/^(.*?>)(.*?)(<.*?)$/gm;
A simple explanation will have to do since a step-by-step such as Demo 1 would take too much time.
This RegEx is multiline. /m
^..........Begin line.
(.*?>)..Lazily capture everything until literal >........[Return as $1]
(.*?)...Then lazily capture everything until................[Return as $2]
(<.*?)..Literal < and lazily capture everything until..[Return as $3]
$...........End line.
The trick is to replace the second capture $2 and leave $1 and $3 alone.
Demo 2
var rgx = /^(.*?>)(.*?)(<.*?)$/gm;
var str = `<start>Apple Bandana Cadillac<stop>
<stop>Grapes Trampoline Ham<stop>
<start>Kebab Matador Pencil<start>
op>Score False Razor<stop>
`;
var res = str.replace(rgx, `$2`);
console.log(res);
I want to match a string between (but not including) these two characters: ? and &
Example string:
localhost/path/doc.html?970441179&token=specialtoken&actionurl=/portletaction/01654/0112
So from the above I want to match the string 970441179
var str = "?samplestring&";
var patt = /[?]([^&]*)[&]/g;
var res = patt.exec(str)[1];
'res' is your desired result.
Try this regex (\d+)(?=&):
var str = "localhost/path/doc.html?970441179&token=specialtoken&actionurl=/portletaction/01654/0112";
console.log(str.match(/(\d+)(?=&)/g));
Note that it will work just for that specific case.
I am using the function match for a search engine, so whenever a user types a search-string I take that string and use the match function on an array containing country names, but it doesn't seem to work.
For example if I do :
var string = "algeria";
var res = string.match(/alge/g); //alge is what the user would have typed in the search bar
alert(res);
I get a string res = "alge": //thus verifying that alge exists in algeria
But if I do this, it returns null, why? and how can I make it work?
var regex = "/alge/g";
var string = "algeria";
var res = string.match(regex);
alert(res);
To make a regex from a string, you need to create a RegExp object:
var regex = new RegExp("alge", "g");
(Beware that unless your users will be typing actual regular expressions, you'll need to escape any characters that have special meaning within regular expressions - see Is there a RegExp.escape function in Javascript? for ways to do this.)
You don't need quotes around the regex:
var regex = /alge/g;
Remove the quotes around the regex.
var regex = /alge/g;
var string = "algeria";
var res = string.match(regex);
alert(res);
found the answer, the match function takes a regex object so have to do
var regex = new RegExp(string, "g");
var res = text.match(regex);
This works fine
I need a javascript regex object that brings back any matches of symbols in a string,
take for example the following string:
input = !"£$[]{}%^&*:#\~#';/.,<>\|¬`
then the following code:
input.match(regExObj,"g");
would return an array of matches:
[[,!,",£,$,%,^,&,*,:,#,~,#,',;,/,.,,,<,>,\,|,¬,`,]]
I have tried the following with no luck.
match(/[U+0021-U+0027]/g);
and I cannot use the following because I need to allow none ascii chars, for example Chinese characters.
[^0-9a-zA-Z\s]
var re = /[!"\[\]{}%^&*:#~#';/.<>\\|`]/g;
var matches = [];
var someString = "aejih!\"£$[]{}%^&*:#\~#';/.,<>\\|¬`oejtoj%";
while(match = re.exec(someString)) {
matches.push(match[1]);
}
Getting
['!','"','[',']','{','}','%','^','&','*',':','#','~','#',''',';','/','.','<','>','\','|','`','%]
What about
/[!"£$\[\]{}%^&*:#\\~#';\/.,<>|¬`]/g
?