Calling characters from a string In JS - javascript

I am currently trying to grab a 9 character string from a title, the start of the list is always "BC-" and then it is always six digits following, so for instance a complete thing would look like - "BC-004352" my problem is that I can grab everything after the "BC-" however if there is something after that like "Words Words BC-004352 Words words" it then grabs the "BC-004352 Words Words". This will mess up my program, so is their any way of only capturing the "BC-004352"? How could I then make the script self executable as at the moment it is running of a button and that isn't helpful
<!--BC-Check six digit-->
<script type="text/javascript">
function bc_check() {
var str = "FUCKCKCKKC BC-040300 Has broken";
var res = str.substring(str.indexOf("BC-") + 0);
document.getElementById("recognize").innerHTML = res;
}
</script>

Or you can do this with Regular Expressions:
const testString = "FCKCKCKKC BC-040300 Has broken";
const regex = /.*?BC-(\d+).*?/; //Capture any number of digits following BC-
const matches = testString.match(regex); //Get the match collection
console.log(matches[1]); //Match collection index 1 holds your number

substring has a second parameter for indexEnd. It doesn't include the character at that index so you'll have to add one to get all of the chars you want. So in this case you'll want to add 10 to the index of "BC-".

Related

Regex to get the first element of each line

I'm trying to get the first element of each line, be it either a number or a string but when the line starts with a number, my current attempt still includes it:
const totalWords = "===========\n\n 1-test\n\n 2-ests \n\n 1 zfzrf";
const firstWord = totalWords.replace(/\s.*/,'')
The output I get :
1-test
2-ests
1 zfzrf
The output I would like:
1
2
1
Alternatively, if you are interested in a non-regexp version (should be faster)
var str = "===========\n\n 1-test\n\n 2-ests \n\n 1 zfzrf";
var res = str.split("\n");
for (row of res) {
let words = row.trim().split(' ');
let firstWord = words[0].trim();
// get first character, parse to int, validate it is infact integer
let element = firstWord.charAt(0);
if (Number.isInteger(parseInt(element))) {
console.log('Row', row);
console.log('Element: ', element);
}
}
Your Regex should skip leading spaces and then capture everything until a space or a dash, so you might want to go with ^\s*([^ -]+).
(See https://regex101.com/r/u7ELiw/1 for application to your examples)
If you additionally know exactly that you are looking for a single digit, you can instead go for ^\s*(\d)
(See https://regex101.com/r/IWhEQ1/1 again for applications)
Maybe im not too sure what you are asking but why are you using something as convoluted as regex when
line.charAt(0)
works pretty well?

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

RegEx to check first two characters must be "1 (numaric)-" in 9 letter word remaing should be alphanumaric

I tried coding in such way that code was not working
var redEx = /^1-[0-9a-zA-Z]{7}/;
document.getElementById("rowidOpty").value.test(redEx)
Example: '1-5S6AW2R': in the string first letter should be numeric and
second character must be "-" and remain alpha-numeric.
It's regexObj.test(string) instead of string.test(regexObj).
See RegExp.prototype.test() for more information.
console.log(/^1-[0-9a-zA-Z]{7}/.test('1-5S6AW2R'))
You have wrong function syntax:
regexp.test([str])
And the right one is:
var regEx = /^1-[0-9a-zA-Z]{7}/;
var string = '1-5S6AW2R';
console.log(regEx.test(string));
pattern = /^[0-9]-(\w+)/g;
console.log('1-5S6AW2R'.match(pattern))
Try this pattern ^[0-9]-(\w+)
Demo Regex
If you want to validate the input matches exactly one numeric, one dash and 7 alphanumerics exactly, use this:
/^[0-9]-[a-zA-Z-0-9]{7}$/;
or if the first can be only the numeral 1:
/^1-[a-zA-Z-0-9]{7}$/;
If you want to search for all occurrences of this pattern in a string that contains a lot of text:
/(^|\s)[0-9]-[a-zA-Z-0-9]{7}(\s|$)/g;
var restrictivePattern = /^[0-9]-[a-zA-Z-0-9]{7}$/;
var loosePattern = /(^|\s)[0-9]-[a-zA-Z-0-9]{7}(\s|$)/g;
var str = '1-A78Z2TE';
var longStr = 'We have 2 different codes 1-AYRJ3F4 and 4-23RJ3F4';
console.log("Validation of string to match pattern: ", str.match(restrictivePattern))
console.log("Multiple matches in string: ", longStr.match(loosePattern))

Javascript Regex to get text between certain characters

I need a regex in Javascript that would allow me to match an order number in two different formats of order URL:
The URLs:
http://store.apple.com/vieworder/1003123464/test#test.com
http://store.apple.com/vieworder/W411234368/test#test.com/AOS-A=
M-104121
The first one will always be all numbers, and the second one will always start with a W, followed by just numbers.
I need to be able to use a single regex to return these matches:
1003123464
W411234368
This is what I've tried so far:
/(vieworder\/)(.*?)(?=\/)/g
RegExr link
That allows me to match:
vieworder/1003123464
vieworder/W411234368
but I'd like it to not include the first capture group.
I know I could then run the result through a string.replace('vieworder/'), but it'd be cool to be able to do this in just one command.
Use your expression without grouping vieworder
vieworder\/(.*?)(?=\/)
DEMO
var string = 'http://store.apple.com/vieworder/1003123464/test#test.com http://store.apple.com/vieworder/W411234368/test#test.com/AOS-A=M-104121';
var myRegEx = /vieworder\/(.*?)(?=\/)/g;
var index = 1;
var matches = [];
var match;
while (match = myRegEx.exec(string)) {
matches.push(match[index]);
}
console.log(matches);
Use replace instead of match since js won't support lookbehinds. You could use capturing groups and exec method to print the chars present inside a particular group.
> var s1 = 'http://store.apple.com/vieworder/1003123464/test#test.com'
undefined
> var s2 = 'http://store.apple.com/vieworder/W411234368/test#test.com/AOS-A='
undefined
> s1.replace(/^.*?vieworder\/|\/.*/g, '')
'1003123464'
> s2.replace(/^.*?vieworder\/|\/.*/g, '')
'W411234368'
OR
> s1.replace(/^.*?\bvieworder\/([^\/]*)\/.*/g, '$1')
'1003123464'
I'd suggest
W?\d+
That ought to translate to "one or zero W and one or more digits".

How to remove the last matched regex pattern in javascript

I have a text which goes like this...
var string = '~a=123~b=234~c=345~b=456'
I need to extract the string such that it splits into
['~a=123~b=234~c=345','']
That is, I need to split the string with /b=.*/ pattern but it should match the last found pattern. How to achieve this using RegEx?
Note: The numbers present after the equal is randomly generated.
Edit:
The above one was just an example. I did not make the question clear I guess.
Generalized String being...
<word1>=<random_alphanumeric_word>~<word2>=<random_alphanumeric_word>..~..~..<word2>=<random_alphanumeric_word>
All have random length and all wordi are alphabets, the whole string length is not fixed. the only text known would be <word2>. Hence I needed RegEx for it and pattern being /<word2>=.*/
This doesn't sound like a job for regexen considering that you want to extract a specific piece. Instead, you can just use lastIndexOf to split the string in two:
var lio = str.lastIndexOf('b=');
var arr = [];
var arr[0] = str.substr(0, lio);
var arr[1] = str.substr(lio);
http://jsfiddle.net/NJn6j/
I don't think I'd personally use a regex for this type of problem, but you can extract the last option pair with a regex like this:
var str = '~a=123~b=234~c=345~b=456';
var matches = str.match(/^(.*)~([^=]+=[^=]+)$/);
// matches[1] = "~a=123~b=234~c=345"
// matches[2] = "b=456"
Demo: http://jsfiddle.net/jfriend00/SGMRC/
Assuming the format is (~, alphanumeric name, =, and numbers) repeated arbitrary number of times. The most important assumption here is that ~ appear once for each name-value pair, and it doesn't appear in the name.
You can remove the last token by a simple replacement:
str.replace(/(.*)~.*/, '$1')
This works by using the greedy property of * to force it to match the last ~ in the input.
This can also be achieved with lastIndexOf, since you only need to know the index of the last ~:
str.substring(0, (str.lastIndexOf('~') + 1 || str.length() + 1) - 1)
(Well, I don't know if the code above is good JS or not... I would rather write in a few lines. The above is just for showing one-liner solution).
A RegExp that will give a result that you may could use is:
string.match(/[a-z]*?=(.*?((?=~)|$))/gi);
// ["a=123", "b=234", "c=345", "b=456"]
But in your case the simplest solution is to split the string before extract the content:
var results = string.split('~'); // ["", "a=123", "b=234", "c=345", "b=456"]
Now will be easy to extract the key and result to add to an object:
var myObj = {};
results.forEach(function (item) {
if(item) {
var r = item.split('=');
if (!myObj[r[0]]) {
myObj[r[0]] = [r[1]];
} else {
myObj[r[0]].push(r[1]);
}
}
});
console.log(myObj);
Object:
a: ["123"]
b: ["234", "456"]
c: ["345"]
(?=.*(~b=[^~]*))\1
will get it done in one match, but if there are duplicate entries it will go to the first. Performance also isn't great and if you string.replace it will destroy all duplicates. It would pass your example, but against '~a=123~b=234~c=345~b=234' it would go to the first 'b=234'.
.*(~b=[^~]*)
will run a lot faster, but it requires another step because the match comes out in a group:
var re = /.*(~b=[^~]*)/.exec(string);
var result = re[1]; //~b=234
var array = string.split(re[1]);
This method will also have the with exact duplicates. Another option is:
var regex = /.*(~b=[^~]*)/g;
var re = regex.exec(string);
var result = re[1];
// if you want an array from either side of the string:
var array = [string.slice(0, regex.lastIndex - re[1].length - 1), string.slice(regex.lastIndex, string.length)];
This actually finds the exact location of the last match and removes it regex.lastIndex - re[1].length - 1 is my guess for the index to remove the ellipsis from the leading side, but I didn't test it so it might be off by 1.

Categories

Resources