trim RegExp result - javascript

I'm using RegExp to extract specific words from a string like the following:
<div class = ''></div>class class
My current RegExp statement is this:
/(<)[^(>)]*(;| |'|&quote;)(class)?( |'|&quote;|=)/gi
In this instance I wan t to match the word 'class' but only if it has specific characters (or ampersands) before and after it. This statement matches:
<div class
out of the original string, I'm using this in a replace method (to insert text where 'class' was) and I want to keep the other character around it, is there any way of trimming this match down to only select(replace) the word 'class' (in this instance)?
Or is there a better way of doing this?
Thanks in advance.

You can use next code to do this job:
var removeSubstring=(function(){
var fn=function($0,$1,$2,$3){return $1+$3;};
return function(str,before,after,removed){
var rg=new RegExp("("+before+")("+removed+")("+after+")","gi");
return str.replace(rg,fn);
};
})();
var str="<div class = ''></div>class class <div class ";
var before="<div ";
var after=" ";
var removed="class";
removeSubstring(str,before,after,removed);
// <div = ''></div>class class <div
But you must ensure what in before, after and removed strings does not contained special RegExp format characters (such as . [ ] ? * and others, see MDN RegExp). Otherwise you must first escape these special characters in before, after and removed strings.
UPDATE:
You also can use valid regular expression for before, after and removed to make more flexible search. For example next code remove letters 'X', 'V' and 'Z' but not remove 'x', 'v' and 'z':
var str="qXd ezrwsvrVa etxceZd";
var before="q|w|e|r";
var after="a|s|d|f";
var removed="z|x|c|v";
removeSubstring(str,before,after,removed);
// "qd ezrwsvra etxced"
If you need to replace substring with another string you can use next function:
function replaceSubstring(str,before,after,removed,inserted){
var rg=new RegExp("("+before+")("+removed+")("+after+")","gi");
return str.replace(rg,function($0,$1,$2,$3){
// $1 is searched "before" substring
// $2 is searched "removed" substring
// $3 is searched "after" substring
return $1+(inserted||"")+$3;
});
};
var str="qXd ezrwsvrVa etxceZd";
var before="q|w|e|r";
var after="a|s|d|f";
var removed="z|x|c|v";
replaceSubstring(str,before,after,removed,"DDDD")
// "qDDDDd ezrwsvrDDDDa etxceDDDDd"

Try this:
var match = /your regex here/.exec(myString)
match = match.replace('class','')

Related

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
}

Regular expression to test exact word with a trailing dot

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
}

regex to get all occurrences with optional next character or end of string

I have a string separated by forward slashes, and wildcards are denoted by beginning with a $:
/a/string/with/$some/$wildcards
I need a regex to get all wildcards (without the "$"), where wildcards can either have more "string" ahead of them (and the next character should always be a forward slash) or will be at the end of the string. Here is where I'm at (it matches to the end of the string rather to the next "/"):
//Just want to match $one
var string = "/a/string/with/$one/wildcard"
var re = /\$(.*)($|[/]?)/g
var m = re.exec(string)
console.log(m);
// [ '$one/wildcard',
// 'one/wildcard',
// '',
// index: 123,
// input: '/a/string/with/$one/wildcard'
// ]
Here was a previous attempt (that doesn't account for wildcards that are at the end of the string):
//Want to match $two and $wildcards
var string = "/a/string/with/$two/$wildcards"
var re = /\$(.*)\//g
var m = re.exec(string)
console.log(m);
// [ '$two/',
// 'two',
// '',
// index: 123,
// input: '/a/string/with/$two/$wildcards'
// ]
I've searched around for matching a character or end of string and have found several answers, but none that try to account for multiple matches. I think I need the ability to match the next character as a / greedily, and then try to match the end of the string.
The desired functionality is to take the input string:
/a/string/with/$two/$wildcards
and transform it to the following:
/a/string/with/[two]/[wildcards]
Thanks in advance! Also, apologies if this has been explicitly covered in detail, I was unable to find a replica after various searches.
I think this should do it:
/\$([^\/]+)/g
And the you can use the replace() function:
"/a/string/with/$two/$wildcards".replace(/\$([^\/]+)/g, "[$1]");
// "/a/string/with/[two]/[wildcards]"
You can use replace function on the string like so:
var s = '/a/string/with/$two/$wildcards';
s.replace(/\$([a-zA-Z]+)/g, '[$1]')';
s will have the value:
/a/string/with/[two]/[wildcards]
Here's a reference to replace documentation https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace

REGEX: Finding the correct occurrence order of some given special characters in a string

I want a regular expression that would be able to find the correct occurrence order of
* | . | # | 'any HTML element type' like 'p' or 'div'
LIKE
var regex = //Some regular expression;
var pattern_1 = "*p.class1#id1.class2";
pattern_1.match(regex); // Should print ['*','p','.','#','.']
var pattern_2 = "p.class1#id1.class2";
pattern_2.match(regex); //Should print ['p','.','#','.']
var pattern_3 = "p#id1.class1.class2";
pattern_3.match(regex); //Should print ['p','#','.','.']
var pattern_4 = "#id.class1.class2";
pattern_4.match(regex); //should print ['#id','.','.']
var pattern_5 = "*#id.class1.class2";
pattern_5.match(regex); //should print ['*','#','.','.']
I am trying my luck with regex = /^\*?[a-zA-Z]*|\#|\./g but it doesn't work
You might be better off matching # and . along with their respective values and filtering the results afterwards:
var regex = /\*|([#.]\w+)|(\w+)/g
matches = pattern_1.match(regex).map(function(x) { return x.match(/^[#.]/) ? x.charAt(0) : x })
or remove the id/class names first, and then match:
matches = pattern_1.replace(/([#.])\w+/g, "$1").match(/[.#*]|\w+/g)
ok I have:
/(\*)|(\.)|([a-zA-Z]+)|(#)/g
the problem with this is that unless you specify all the possible html elements that you can capture like div, span etc then it will match all strings including class and id names.
Hope this helps anyway.
Edit live on Debuggex

Categories

Resources