Reputation: 13
I am trying to find a regex solution to check if a string matches all conditions + /
forward slashes.
Current code:
var specialChars = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g;
This will match true if a string looks like so: 4!@#$
.
However it does not work if the string looks like this: 5/6/2019
This is how I'm implementing this check, basically I have a function that takes in an long string. And what I'm trying to do is pluck out the tracking ID then create a link out of it.
My test cases are also in the demo, the date test is the one that fails, since the linkCreator function ends up linking to the date:
https://jsfiddle.net/cojuevp5/
var linkCreator = function(value) {
var strings = value.split(' ');
var aHref = '<a href="http://www.google.com/search?q=';
var targetBlank = '" target="_blank" style="text-decoration: underline">';
var trackingString = strings.reduce(function(prevVal, currVal, idx) {
var specialChars = /^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g;
// Does val start with number and not contain special characters including /
var link = currVal.match(/^\d/) && !currVal.match(specialChars) ?
aHref + currVal + targetBlank + currVal + '</a>' :
currVal;
return idx == 0 ? link : prevVal + ' ' + link;
}, '');
console.log(trackingString);
}
const case1 = '434663008870'
const case2 = '4S4663008870'
const case3 = '4S4663008870 PS'
const case4 = 'SHD FX 462367757727 PS'
const case5 = 'SHD FX 429970755485, R'
const case6 = 'SHD HEADER TRACKING PS'
const case7 = 'N/A'
const case8 = 'AF SHD FX 462367757727 PS'
const case9 = '4/7/2019'
const case10 = '4!@#$%^&'
const value = case9
const link = linkCreator(value)
console.log(link)
Upvotes: 1
Views: 59
Reputation: 27723
You might want to add a \/
and that would likely solve your problem:
^([A-z0-9!\/@#$%^&*)(+=._-]+)$
Just like Barmar says, you do not need to escape all chars inside []
:
I'm guessing that this may be what you might want to match:
You might just use this tool and design any expression that you wish.
This graph shows how your expression works:
Upvotes: 1