Cannot extract parts of a string - javascript

I have a string like this : SPList:6E5F5E0D-0CA4-426C-A523-134BA33369D7?SPWeb:C5DD2ADA-E0C4-4971-961F-233789297FE9:.
Using Javascript, I would like to extract the two IDs (which can be different) : 6E5F5E0D-0CA4-426C-A523-134BA33369D7 and C5DD2ADA-E0C4-4971-961F-233789297FE9.
I'm using this regular expression : ^SPList\:(?:[0-9A-Za-z\-]+)\?SPWeb\:(?:[0-9A-Za-z\-]+)\:$.
I expect this expression to extract into two matching groups the two IDs.
By now, my code is :
var input = "SPList:6E5F5E0D-0CA4-426C-A523-134BA33369D7?SPWeb:C5DD2ADA-E0C4-4971-961F-233789297FE9:";
var myregex = /^SPList\:(?:[0-9A-Za-z\-]+)\?SPWeb\:(?:[0-9A-Za-z\-]+)\:$/g;
var match = input.match(myregex);
var listId = match[0];
var webId = match[1];
However, this is not working as expected. The first match contains the whole string, and the second match is undefined.
What is the proper way to extract my ID's?
Here is a jsfiddle that illustrate my issue.

This should suit your needs:
var regex = /^SPList:([0-9A-F-]+)[?]SPWeb:([0-9A-F-]+):$/g;
var match = regex.exec(input);
var listId = match[1];
var webId = match[2];
I simply replaced the non-capturing groups of your initial regex by capturing groups, and used regex.exec(input) instead of input.match(regex) to get the captured data. Also, since the IDs seem to be hexadecimal values, I used A-F instead of A-Z.

try this:
var myregex = /[^\:]([0-9A-Z\-]+)[^\?|\:]/g;
var match = input.match(myregex);
alert("listID: " + match[1] + "\n" + "webID: " + match[3]);

Related

How to replace numbers with an empty char

i need to replace phone number in string on \n new line.
My string: Jhony Jhons,jhon#gmail.com,380967574366
I tried this:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366'
var regex = /[0-9]/g;
var rec = str.trim().replace(regex, '\n').split(','); //Jhony Jhons,jhon#gmail.com,
Number replace on \n but after using e-mail extra comma is in the string need to remove it.
Finally my string should look like this:
Jhony Jhons,jhon#gmail.com\n
You can try this:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366';
var regex = /,[0-9]+/g;
str.replace(regex, '\n');
The snippet above may output what you want, i.e. Jhony Jhons,jhon#gmail.com\n
There's a lot of ways to that, and this is so easy, so try this simple answer:-
var str = 'Jhony Jhons,jhon#gmail.com,380967574366';
var splitted = str.split(","); //split them by comma
splitted.pop(); //removes the last element
var rec = splitted.join() + '\n'; //join them
You need a regex to select the complete phone number and also the preceding comma. Your current regex selects each digit and replaces each one with an "\n", resulting in a lot of "\n" in the result. Also the regex does not match the comma.
Use the following regex:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366'
var regex = /,[0-9]+$/;
// it replaces all consecutive digits with the condition at least one digit exists (the "[0-9]+" part)
// placed at the end of the string (the "$" part)
// and also the digits must be preceded by a comma (the "," part in the beginning);
// also no need for global flag (/g) because of the $ symbol (the end of the string) which can be matched only once
var rec = str.trim().replace(regex, '\n'); //the result will be this string: Jhony Jhons,jhon#gmail.com\n
var str = "Jhony Jhons,jhon#gmail.com,380967574366";
var result = str.replace(/,\d+/g,'\\n');
console.log(result)

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");

Get all characters except hyphen and brackets from string using javascript regex

I have a string like this:
var myString = "MyString-[ADDAAD]-isGreat";
I want to extract this string into 3 parts:
var stringOne = "MyString-";
var stringTwo = "ADDAAD";
var stringThree = "-isGreat";
I know how to get the string between the two square brackets:
var matches = patternString.match(/\[(.*?)\]/);
now matches[1] contains ADDAAD
But how can I get the other two parts?
Select every character except -, [ and ] using bottom regex.
var myString = "MyString-[ADDAAD]-isGreat";
var parts = myString.match(/[^-\[\]]+/g);
console.log(parts);
So if you want to store values in custom variable, use bottom code
var stringOne = parts[0];
var stringTwo = parts[1];
var stringThree = parts[2];
You may split the string with your regex. Note that all the capturing group contents will be also part of the resulting array. To avoid empty items, you may add .filter(Boolean) after split().
See a JS demo below:
var myString = "MyString-[ADDAAD]-isGreat";
console.log(myString.split(/\[(.*?)]/).filter(Boolean));
console.log("s1-[s2]".split(/\[(.*?)]/).filter(Boolean));
Note you do not have to escape a ] used outside character classes, it is always parsed as a literal closing bracket if there is no corresponding [ before it.

get particular strings from a text that separated by underscore

I am trying to get the particular strings from the text below :
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
From this i have to get the following strings: "LAST", "BRANCH" and "JENKIN".
I used the code below to get "JENKIN";
var result = str.substr(str.lastIndexOf("_") +1);
It will get the result "JENKIN.bin". I need only "JENKIN".
Also the input string str sometimes contains this ".bin" string.
with substring() function you can extract text you need with defining start and end position. You have already found the start position with str.lastIndexOf("_") +1 and adding end position with str.indexOf(".") to substring() function will give you the result you need.
var result = str.substring(str.lastIndexOf("_") +1,str.indexOf("."));
It depends on how predictable the pattern is. How about:
var parts = str.replace(/\..+/, '').split('_');
And then parts[0] is 001AN, parts[1] is LAST, etc
You can use String.prototype.split to split a string into an array by a given separator:
var str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin';
var parts = str.split('_');
// parts is ['001AN', 'LAST', 'BRANCH', 'HYB', '1hhhhh5', 'PBTsd', 'JENKIN.bin'];
document.body.innerText = parts[1] + ", " + parts[2] + " and " + parts[6].split('.')[0];
You could do that way:
var re = /^[^_]*_([^_]*)_([^_]*)_.*_([^.]*)\..*$/;
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var matches = re.exec(str);
console.log(matches[1]); // LAST
console.log(matches[2]); // BRANCH
console.log(matches[3]); // JENKIN
This way you can reuse your RegExp anytime you want, and it can be used in other languages too.
Try using String.prototype.match() with RegExp /([A-Z])+(?=_B|_H|\.)/g to match any number of uppercase letters followed by "_B" , "_H" or "."
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var res = str.match(/([A-Z])+(?=_B|_H|\.)/g);
console.log(res)
I don't know why you want to that, but this example would be helpful.
It will be better write what exactly you want.
str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin'
find = ['LAST', 'BRANCH', 'JENKINS']
found = []
for item in find:
if item in str:
found.append(item)
print found # ['LAST', 'BRANCH']

Javascript Regex replace by group

Suppose you have this string: url?param1=something&param2=something&param3=something which can also be only url?param1=something.
How would you do to convert param1=something to param1=anotherthing ?
I am able to do it this way:
var regex = /param1=.*(&|$)/;
var string = 'url?param1=something&param2=something&param3=something';
var newValue = 'anotherthing';
string.replace(regex, 'param1='+newValue);
However, I do not like the fact of repeating all the search term, so I'm asking if it is possible to group the needed pattern to replace, in this case would be .* and replace only that.
For example, saying that $1 belongs to group 1. This is fictitious.
var regex = /param1=(.*)(&|$)/;
var string = 'url?param1=something&param2=something&param3=something';
var newValue = 'anotherthing';
string.replace(regex, $1, newValue);
Try this:
var string = 'url?param1=something&param2=something&param3=something';
alert(string.replace(/(param1)([^&]+)/, '$1=newparam1'));
if you want to set multiple parameters to the same value
alert(string.replace(/(param1|param2)([^&]+)/g, '$1=newparam'));
Add another capture group...
var regex = /(param1=)([^&]*)/;
var string = 'url?param1=something&param2=something&param3=something';
var newValue = 'anotherthing';
string.replace(regex, "$1" + newValue);

Categories

Resources