Regular expression to test exact word with a trailing dot - javascript

I am having a dynamic variable which I need to match against a source.
Source: 'text clientLogin padding float';
search: '.clientLog'
The search text has a leading dot('.') which should be omitted while comparing.
For the above example I should:
Get the part of search after '.'(dot)
Check the source for the search text i.e clientLog & return true if whole word matches.(in this example it should return false as source has clientLogin).
I am trying to use RegEx to achieve this
var regEx = new RegExp(k); // k is the search text
if(regEx.test(classNames)){....
Above code is inside jQuery.each,k is the key of the object which is being iterated.I did not figure out how to omit the '.' but read somewhere to implement Word Boundries for the exact match.
Please suggest.
thanks

Try this:
var
source = 'text clientLogin padding float',
search = '.clientLog',
pattern = '\\b'+search.replace(/^\./, '')+'\\b',
result = new RegExp(pattern).test(source);
Notes:
We strip off the leading '.' from the search string while building the pattern
We use word boundary markers (\b). This helps ensure that "login" is not considered a valid match for "log", for example, like in your case.
The double-escaping (\\b) is necessary as we're building our pattern as a string - this is necessary for dynamic patterns fed to the RegExp constructor.

Stripping text
In JavaScript, you can strip text with the substring() method like this:
var str = "Hello World!";
var sub_str = str.substring(1, str.length);
In substring(x, y), x is the starting index of the new string, y is the ending index. The indecies in JavaScript start at 0, so we have to use the next index to omit the first character in the string.
You can also read it up here on W3Schools.
Regular Expressions
You can search RegEx patterns in strings like this:
var str = "Hello World!";
var pos = str.search(/World/); // Attention: No quotes here!
pos equals the index of the first match of the given expression. If your expression did not match your string, then pos will equal -1.
Note, that str.search(/World/); is basicly the same as str.search(new RegExp("World"));
You can also read it up here on W3Schools.
To check, if your string contains that classname, you could do this:
var str = "classname1 classname2 classname3";
var search_str = ".classname2";
if(str.search(new RegExp("\\b(" + search_str.substring(1, search_str.length) + ")\\b")) > -1){
// classname found
} else {
//classname not found
}

Related

JavaScript get first name and last name from string as array

I have a string that has the following format: <strong>FirstName LastName</strong>
How can I change this into an array with the first element firstName and second lastName?
I did this, but no luck, it won't produce the right result:
var data = [myString.split('<strong>')[1], myString.split('<strong>')[2]]
How can I produce ["firstName", "lastName"] for any string with that format?
In order to parse HTML, use the best HTML parser out there, the DOM itself!
// create a random element, it doesn't have to be 'strong' (e.g., it could be 'div')
var parser = document.createElement('strong');
// set the innerHTML to your string
parser.innerHTML = "<strong>FirstName LastName</strong>";
// get the text inside the element ("FirstName LastName")
var fullName = parser.textContent;
// split it into an array, separated by the space in between FirstName and LastName
var data = fullName.split(" ");
// voila!
console.log(data);
EDIT
As #RobG pointed out, you could also explicitly use a DOM parser rather than that of an element:
var parser = new DOMParser();
var doc = parser.parseFromString("<strong>FirstName LastName</strong>", "text/html");
console.log(doc.body.textContent.split(" "));
However, both methods work perfectly fine; it all comes down to preference.
Just match everything between <strong> and </strong>.
var matches = "<strong>FirstName LastName</strong>".match(/<strong>(.*)<\/strong>/);
console.log(matches[1].split(' '));
The preferred approach would be to use DOM methods; create an element and get the .textContent then match one or more word characters or split space character.
let str = '<strong>FirstName LastName</strong>';
let [,first, last] = str.split(/<[/\w\s-]+>|\s/g);
console.log(first, last);
/<[/\w\s-]+>|\s/g
Splits < followed by one or more word, space or dash characters characters followed by > character or space to match space between words in the string.
Comma operator , within destructuring assignment is used to omit that index from the result of .split() ["", "FirstName", "LastName", ""].
this is my approach of doing your problem. Hope it helps!
var str = "<strong>FirstName LastName</strong>";
var result = str.slice(0, -9).substr(8).split(" ");
Edit: it will only work for this specific example.
Another way to do this in case you had something other than an html
var string = "<strong>FirstName LastName</strong>";
string = string.slice(0, -9); // remove last 9 chars
string = string.substr(8); // remove first 8 chars
string = string.split(" "); // split into an array at space
console.log(string);

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

RegExp case insensitive search for whole word with variable

I have an object with strings properties I want to compare to multiple user inputs using case insensitivity. My goal is to match input strings to object strings to increment the associated value by 1 (if it's a match).
var objArr = [
{"O": 0},
{"foo": 0},
{"faa": 0},
{"A": 0}
];
Everything is working smoothly except for the case insensitivity. The RegExp method I used just looks for one letter instead of the whole word. I'm probably not using the right syntax, but I can't find results on google which explain the /i flag along with a variable.
My closest try was :
var re = new RegExp(b, "i"); //problem here
if (allinputs[i].value.match(re)) { //and here
This code indeed allows case insensitivity but it doesn't look for the whole object property string and stops for letters. For exemple typing "foo" will result in a match to "O" because it contains the letter "O", and the property "O" is before "foo". Accordingly, typing "faa" matches to "faa" and not "A", because "faa" is before "A" in the objects array. Strings that don't exist in my object like "asfo" will still be matched to "O" because of the one common letter.
Is there a way to search for the whole property string with case insensivity using the regExp /i flag ? I want to avoid using .toUpperCase() or .toLowerCase() methods if possible.
Fiddle here : https://jsfiddle.net/Lau1989/b39Luhcu/
Thanks for your help
To check that a regex matches the entire string, you can use the assert beginning character (^) and assert end ($).
For example, hello matches e but not ^e$.
For your code, just prepend ^ to the regex and append $:
var re = new RegExp("^" + b + "$", "i");
fiddle
Edit: Some characters have special meanings in regexes (^, $, \, ., *, etc). If you need to use any of these characters, they should be escaped with a \. To do this, you can use this simple replace:
str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
So, your regex will end up being
new RegExp("^" + b.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + "$", "i");
See this question for more about escaping a regex.
You could also just convert the two strings to lowercase and then compare them directly. This will allow you to use special characters as well.
if (stringA.toLowerCase() == stringB.toLowerCase())) {
...
}
Your approach was almost right, but you need limitate your regular expression to avoid an any match using ^ (start of string) and $ (end of string).
Here is a code that I made that may fit to your need:
function process()
{
var allinputs = document.querySelectorAll('input[type="text"]');
var list = new Array();
var input = "";
objArr.map(function(value, index, array){ list.push(Object.keys(value))})
for(var i = 0; i < allinputs.length; i++)
{
input = allinputs[i];
if(input.value)
{
list.map(function( item, index, array ) {
var re = new RegExp("^"+input.value+"$", "i");
if(item.toString().match(re))
{
allinputs[i].value = "1";
objArr[index][item] += 1;
allinputs[i].style.backgroundColor = "lime";
document.getElementById('output').innerHTML += item + " : " + objArr[index][item] + "<br />";
}
});
}
}
}
The first thing here is create a list of keys from your objArr, so we can access the key names easily to match with what you type
objArr.map(function(value, index, array){ list.push(Object.keys(value))})
Then the logic stills the same as you already did, a for loop in all inputs. The difference is that the match will occur on list array instead of the objArr. As the index sequence of list and objArr are the same, it's possible to access the object value to increment.
I used the .map() function in the list array, bit it's also possible use a for loop if you prefer, both method will work.
I hope this help you!

Regex to store only one matching element found in a string-js

I may be asking a stupid Quest, but I'd really like to know if there is there a regular expression to get only the first matched letter from a string?Eg:
var string = "abcdaeee";
var value = 'a';
the value and the string field is dynamic hence they could vary. In above case I'm willing to get only the first matching letter found to the var 'value' (which is 'a') in the string.I currently have this regex:
regex = new RegExp("(" + value + ")", "i");
string.match(regex)
instead can i have something like: o/p: a,a
string.match(someValidRegex)// to o/p: a
but this ones gets all the matching a's from the string. Is there a way in regex to display only the first occurrence of a matching element?
Eg o/p: ["a"]
Thanks!
Apologies this is the solution for the first matched letter not using regex
If you just want to get the first matched letter of a string i think that regex is a bit overkill.
This would work
function getFirstMatchedLetter(str,letter){
var letterPosition = str.search(letter);
return str.charAt(letterPosition);
}
getFirstMatchedLetter("hello","l");
Alternatively, if possible, you could use two regexes. One to extract the string, then the other to parse the extracted string to get your character or whatever.
var str = "blah blah blah something blah blah blah";
var matched = str.match(/something/);
var character_matched = matched[0].match(/e/);
the variable character_matched should now contain your letter. You can alter 'something' in the var matched line and 'e' in the var character_matched line to suit your needs. However, my question is: what are you extracting just the character in a particular word/string for?
Also, if you're matching a regex more than once, check if you have globals on.
Alternatively:
var str = "hello";
var letter = "p";
var exists = str.search(letter);
if (exists != -1)
{
# character is in the string, do something
}
else
{
# character not in string, do something else
}

Categories

Resources