regex for string to get customerID - javascript

I am looking for the word customerID number in a string. Customer id would be in this format customerID{id}
so look at some different strings I would have
myVar = "id: 1928763783.Customer Email: test#test.com.Customer Name:John Smith.CustomerID #123456.";
myVar = "id: 192783.Customer Email: test1#test.com.Customer Name:Rose Vil.CustomerID #193474.";
myVar = "id: 84374398.Customer Email: test2#test.com.Customer Name:James Yuem.";
Ideally I wanna be able to check if a CustomerID exists or not. If it does exists then I want to see what it is. I know we can use regext but not sure howd that look
thanks

var match = myVar.match(/CustomerID #(\d+)/);
if (match) id = match[1];

I'm not 100% farmiliar with the syntax but I'd say: "(CustomerID #([0-9]+).)"
I think this is a valid regular expression for what you're looking for, it would check if a string had 'CustomerID' followed by a space, a numer sign and then a sequence of numbers. By surrouding the numbers with brackets, they can be captured by refrencing bracket 2 if it found something
I'm not sure if the brackets or period need a \ before them in this syntax or not. Sorry I can't be of more help but I hope this helps in some way.

Play around to get this to work for your needs:
// case-insensitive regular expression (i indicates case-insensitive match)
// that looks for one of more spaces after customerid (if you want zero or more spaces, change + to *)
// optional # character (remove ? if you don't want optional)
// one or more digits thereafter, (you can specify how long of an id to expect with by replacing + with {length} or {min, max})
var regex = /CustomerID\s+#?(\d+)/i;
var myVar1 = "id: 1928763783.Customer Email: test#test.com.Customer Name:John Smith.CustomerID #123456.";
var match = myVar1.match(regex);
if(match) { // if no match, this will be null
console.log(match[1]); // match[0] is the full string, you want the second item in the array for your first group
}

Related

How to find a word that has surrounded with indicator? javascript

I have a string below which has some identifier to get an specific word on it.
string example: "I will c#hec*k on it"
the "#" indicates starting, and the "*" indicates for last.
I want to get two strings.
check - the whole word that has "#" and "*" on it.
hec - string that was surrounded.
I have started to use the below code, but it seems does not work.
sentence.split('#').pop().split('*')[0];
Somebody knows how to do it. would appreciate it thanks
var s = "I will c#hec*k on it"
console.log(s.match(/(?<=#)[^*]*(?=\*)/)) // this will print ["hec"]
console.log(s.match(/\w*#[^*]*\*\w*/).map(s => s.replace(/#(.*)\*/, "$1"))) // this will print ["check"]
where:
(?<=#) means "preceded by a #"
[^*]* matches zero or more characters that are not a *
(?=\*) means "followed by a *"
\w* matches zero or more word characters
(.*) is a capturing group (referenced by $1) matching any number of any kind of character (except for newlines)
I would try something like this with Javascript,
there might be a better approach with regex though.
let sentence = "I will c#hec*k on it";
sentence.split(" ").forEach(word => {
if(word.includes("#") && word.includes("*")){
let betweenChars = word.substring(
word.lastIndexOf("#") + 1,
word.lastIndexOf("*")
)
console.log('Between chars: ', betweenChars);
let withoutChars = word.replace(/[#*]/g,"");
console.log('Without chars: ', withoutChars);
}
});

Return full string if partial string is found Javascript/Jquery

Unable to retrieve full string if partially matched.
Example:
src = 'The expression $ a{\color{blue}{x}}^2 + b{\color{blue}{x}} + c$ is said to be quadratic when TAtrimg001a.svg is \neq 0$'
search for "svg" > should return TAtrimg001a.svg
I am trying to search and find the string "svg". If the "svg" exists then it should return TAtrimg001a.svg not just its location or the word svg itself but the complete svg filename.
In reply to a comment...
I tried finding the match in following differenet ways, but they do really work for my requirment, example:
var res = str.match(/svg/ig);
var res = str.search("svg");
var res = str.indexOf( "svg" )
Straightforward with regex. The string .match method takes a regex and returns either:
null if there was no match.
An array otherwise, where the first element is the entire matched string, and the remaining elements are each respective capture group (if any).
So for this case, you just want the whole match, so just taking that first item should be fine. The example regex below just looks for any string of non-whitespace characters that ends with .svg. You may want to broaden or tighten that to meet your exact use case.
src = 'The expression $ a{\color{blue}{x}}^2 + b{\color{blue}{x}} + c$ is said to be quadratic when TAtrimg001a.svg is \neq 0$'
function findFileName(str, ext) {
const match = str.match(new RegExp(`\\w+\\.${ext}`));
return match && match[0]
}
console.log(findFileName(src, "svg"))
Minor Note: When passing a string to the RegExp constructor, backslashes must be doubled, since the first backslash escapes the second as part of the string.
In ES6 you can do something like const result = str.endsWith(".svg") ? str : null;, which will store in result variable full file name (if it ends with ".svg" part, in other words, has svg format), or null (if it doesn't):
function checkIsFileOfType(str, fileType) {
return str.endsWith("." + fileType) ? str : null;
}
console.log(checkIsFileOfType("TAtrimg001a.svD", "svg"));
console.log(checkIsFileOfType("TAtrimg001a.svg", "svg"));

Regex match cookie value and remove hyphens

I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens. I would like to replace the hyphens with a space and set to a variable. Javascript or jQuery.
As an example, the larger string has a name and value like this within it:
facility=34222%7CConner-Department-Store;
(notice the leading "C")
So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex. Then break it down to "Conner Department Store"
var cookie = document.cookie;
var facilityValue = cookie.match( REGEX ); ??
var test = "store=874635%7Csomethingelse;facility=34222%7CConner-Department-Store;store=874635%7Csomethingelse;";
var test2 = test.replace(/^(.*)facility=([^;]+)(.*)$/, function(matchedString, match1, match2, match3){
return decodeURIComponent(match2);
});
console.log( test2 );
console.log( test2.split('|')[1].replace(/[-]/g, ' ') );
If I understood it correctly, you want to make a phrase by getting all the words between hyphens and disallowing two successive Uppercase letters in a word, so I'd prefer using Regex in that case.
This is a Regex solution, that works dynamically with any cookies in the same format and extract the wanted sentence from it:
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Demo:
var str = "facility=34222%7CConner-Department-Store;";
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Explanation:
Use this Regex (/([A-Z][a-z]+)-?/g to match the words between -.
Replace any - occurence in the matched words.
Then just join these matches array with white space.
Ok,
first, you should decode this string as follows:
var str = "facility=34222%7CConner-Department-Store;"
var decoded = decodeURIComponent(str);
// decoded = "facility=34222|Conner-Department-Store;"
Then you have multiple possibilities to split up this string.
The easiest way is to use substring()
var solution1 = decoded.substring(decoded.indexOf('|') + 1, decoded.length)
// solution1 = "Conner-Department-Store;"
solution1 = solution1.replace('-', ' ');
// solution1 = "Conner Department Store;"
As you can see, substring(arg1, arg2) returns the string, starting at index arg1 and ending at index arg2. See Full Documentation here
If you want to cut the last ; just set decoded.length - 1 as arg2 in the snippet above.
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1)
//returns "Conner-Department-Store"
or all above in just one line:
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1).replace('-', ' ')
If you want still to use a regular Expression to retrieve (perhaps more) data out of the string, you could use something similar to this snippet:
var solution2 = "";
var regEx= /([A-Za-z]*)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/;
if (regEx.test(decoded)) {
solution2 = decoded.match(regEx);
/* returns
[0:"facility=34222|Conner-Department-Store",
1:"facility",
2:"34222",
3:"Conner-Department-Store",
index:0,
input:"facility=34222|Conner-Department-Store;"
length:4] */
solution2 = solution2[3].replace('-', ' ');
// "Conner Department Store"
}
I have applied some rules for the regex to work, feel free to modify them according your needs.
facility can be any Word built with alphabetical characters lower and uppercase (no other chars) at any length
= needs to be the char =
34222 can be any number but no other characters
| needs to be the char |
Conner-Department-Store can be any characters except one of the following (reserved delimiters): :/?#[]#;,'
Hope this helps :)
edit: to find only the part
facility=34222%7CConner-Department-Store; just modify the regex to
match facility= instead of ([A-z]*)=:
/(facility)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/
You can use cookies.js, a mini framework from MDN (Mozilla Developer Network).
Simply include the cookies.js file in your application, and write:
docCookies.getItem("Connor Department Store");

Why is this regex matching also words within a non-capturing group?

I have this string (notice the multi-line syntax):
var str = ` Number One: Get this
Number Two: And this`;
And I want a regex that returns (with match):
[str, 'Get this', 'And this']
So I tried str.match(/Number (?:One|Two): (.*)/g);, but that's returning:
["Number One: Get this", "Number Two: And this"]
There can be any whitespace/line-breaks before any "Number" word.
Why doesn't it return only what is inside of the capturing group? Am I misundersating something? And how can I achieve the desired result?
Per the MDN documentation for String.match:
If the regular expression includes the g flag, the method returns an Array containing all matched substrings rather than match objects. Captured groups are not returned. If there were no matches, the method returns null.
(emphasis mine).
So, what you want is not possible.
The same page adds:
if you want to obtain capture groups and the global flag is set, you need to use RegExp.exec() instead.
so if you're willing to give on using match, you can write your own function that repeatedly applies the regex, gets the captured substrings, and builds an array.
Or, for your specific case, you could write something like this:
var these = str.split(/(?:^|\n)\s*Number (?:One|Two): /);
these[0] = str;
Replace and store the result in a new string, like this:
var str = ` Number One: Get this
Number Two: And this`;
var output = str.replace(/Number (?:One|Two): (.*)/g, "$1");
console.log(output);
which outputs:
Get this
And this
If you want the match array like you requested, you can try this:
var getMatch = function(string, split, regex) {
var match = string.replace(regex, "$1" + split);
match = match.split(split);
match = match.reverse();
match.push(string);
match = match.reverse();
match.pop();
return match;
}
var str = ` Number One: Get this
Number Two: And this`;
var regex = /Number (?:One|Two): (.*)/g;
var match = getMatch(str, "#!SPLIT!#", regex);
console.log(match);
which displays the array as desired:
[ ' Number One: Get this\n Number Two: And this',
' Get this',
'\n And this' ]
Where split (here #!SPLIT!#) should be a unique string to split the matches. Note that this only works for single groups. For multi groups add a variable indicating the number of groups and add a for loop constructing "$1 $2 $3 $4 ..." + split.
Try
var str = " Number One: Get this\
Number Two: And this";
// `/\w+\s+\w+(?=\s|$)/g` match one or more alphanumeric characters ,
// followed by one or more space characters ,
// followed by one or more alphanumeric characters ,
// if following space or end of input , set `g` flag
// return `res` array `["Get this", "And this"]`
var res = str.match(/\w+\s+\w+(?=\s|$)/g);
document.write(JSON.stringify(res));

Replace all in JavaScript Regex

i have below string from which I have to extract username and ID.
This is a string which has a #[User Full Name](contact:1) data inside.
To get username and contact id from above string I am using this regex pattern.
var re = /\#\[(.*)\]\(contact\:(\d+)\)/;
text = text.replace(re,"username:$1 with ID: $2");
// result == username: User Full Name with ID: 1
It works perfectly now issue is I have multiple usernames in string, I tried using /g (global) but its not replacing properly:
Example string:
This is a string which has a #[User Full Name](contact:1) data inside. and it can also contain many other users data like #[Second Username](contact:2) and #[Third username](contact:3) and so many others....
when used global I get this result:
var re = /\#\[(.*)\]\(contact\:(\d+)\)/g;
text = text.replace(re,"username:$1 with ID: $2");
//RESULT from above
This is a string which has a user username; User Full Name](contact:1) data inside. and it can also contain many other users data like #[[Second Username](contact:2) and #[Third username and ID: 52 and so many others....
You just need a non greedy ? match in your first capture group. By having .* you are matching the most amount possible while if you use .*?, it matches the least amount possible.
/#\[(.*?)\]\(contact:(\d+)\)/
And if the word contact is not always there, you could do..
/#\[(.*?)\]\([^:]+:(\d+)\)/
See working demo
Can't say I can see how your resulting string is going to be usable. How about something like this...
var re = /#\[(.*?)\]\(contact:(\d+)\)/g;
var users = [];
var match = re.exec(text);
while (match !== null) {
users.push({
username: match[1],
id: match[2]
});
match = re.exec(text);
}

Categories

Resources