I am trying to get just a part of a string with a regex
this is the string i am testing
class1 container _box _box_CEC493
the string is a series of classes applied to an element.
what i would like to get is just CEC493 which changes since the regex will be applied to a bunch of different elements (therefore string like the one above)
the regex i am using now is
/\s_box_([0-9a-zA-Z]+)/
which returns
_box_CEC493, CEC493
How can i modify it in order to get just the second value (CEC493)?
Thank you
You could probably just split the string:
var str = "class1 container _box _box_CEC493";
var match = str.split('_').pop();
alert(match);
DEMO
The standard way regexes come back is like this:
[0]: Whole result
[1]: First parentheses capture group
etc
So the standard way that people access these is with result[1]. Does that cause any issues in your case?
[updated]
instead of selecting all characters, select until an unwanted character,, and since you are selecting from a number of classes, it is possible that you have the _box_.. class alone without a space before it, so don't use space at the beginning of your regex selector.
str.match(/_box_([^\s]*)/)[1]
jsfiddle
Related
I want to get all the words, except one, from a string using JS regex match function. For example, for a string testhello123worldtestWTF, excluding the word test, the result would be helloworldWTF.
I realize that I have to do it using look-ahead functions, but I can't figiure out how exactly. I came up with the following regex (?!test)[a-zA-Z]+(?=.*test), however, it work only partially.
http://refiddle.com/refiddles/59511c2075622d324c090000
IMHO, I would try to replace the incriminated word with an empty string, no?
Lookarounds seem to be an overkill for it, you can just replace the test with nothing:
var str = 'testhello123worldtestWTF';
var res = str.replace(/test/g, '');
Plugging this into your refiddle produces the results you're looking for:
/(test)/g
It matches all occurrences of the word "test" without picking up unwanted words/letters. You can set this to whatever variable you need to hold these.
WORDS OF CAUTION
Seeing that you have no set delimiters in your inputted string, I must say that you cannot reliably exclude a specific word - to a certain extent.
For example, if you want to exclude test, this might create a problem if the input was protester or rotatestreet. You don't have clear demarcations of what a word is, thus leading you to exclude test when you might not have meant to.
On the other hand, if you just want to ignore the string test regardless, just replace test with an empty string and you are good to go.
Is it possible to grab custom attribute like this 'something-20'
say for example it is in <div class="somecustomClass something-20"></div>
I want to grad the 19 so that I can manipulate it, because the css has block from something-1 to something-100
I used below code to retrieve tab id :
tabId = $('li').find('a').attr('href').replace('#tab', '');
is it the same approach?
That's not a custom attribute, it's a class. You'd have to get the entire class string, then probably use a regular expression to find the value you want.
It would be easier to use data- attributes:
<div class="somecustomClass" data-something="20"></div>
JS:
var value = $('.somecustomClass').data('something'); // 20
If you want it to be a custom attribute I suggest you do what Jason said in his answer. But if you want to grab the something-# elements and do something with them you can do the following.
for(var i=1;i<=100;i++) {
var el = $('.something-'+i);
//do something with the element to manipulate it
}
Similar. What the tab id thing does is 3 things
Part 1 is selecting the right element.
Part 2 is getting the value of the attribute that contains the data we want
Part 3 is getting the specific bit of the data that we want with a regular expression
For part 1, I'm not sure what you're using to identify these blocks in order to select them.
You could have $('[class^="something"]') to get all the elements that have a class that starts with the text 'something', but that will be quite slow. If you can use something like $('.somecustomClass') it will perform better.
If you just wanted to adapt the first matching element you came across, you could do this:
var myNumber = $('.somecustomClass')[0].className.replace(/.*?\bsomething\-(\d+).*/gi, "$1");
Apologies if you are already familiar with regular expressions, but for other readers this is a breakdown of what it does:
.*? means non-greedily select zero or more characters, \b means word boundary, then it finds the text 'something-' followed by one or more digits. Putting brackets around it captures what it finds there. Just in case you have classes after than, it has .* to get zero or more characters to find them too. /gi on the end of that means look globally through the class and i means be case-insensitive. $1 as the second argument of the replace function is the captured digits.
In a list of footnote references for an article, I want to select all occurences of "(en)" and wrap them in some so that I can apply bold style to them as well as a right margin.
How to do that with jQuery ?
lets say you can get all your data into a string:
var myString = $('#footnotes').html();
Since you don't need regex you can split into an array and rejoin.. ex:
var newString = myString.split("(en)").join("<span class='en-element'>(en)</span>");
$('#footnotes').html(newString);
Using regex to find the "(en)"'s, and then using string.replace to replace them with the content you want.
I know when to use regex but am not too familiar with it's sintaxys, so sorry for not providing the exact code, take a look at this post in which they tried to do the same but finding and replacing it with \n
jQuery javascript regex Replace <br> with \n
Say I have a string "&something=variable&something_else=var2"
I want to match between &something= and &, so I'll write a regular expression that looks like:
/(&something=).*?(&)/
And the result of .match() will be an array:
["&something=variable&", "&something=", "&"]
I've always solved this by just replacing the start and end elements manually but is there a way to not include them in the match results at all?
You're using the wrong capturing groups. You should be using this:
/&something=(.*?)&/
This means that instead of capturing the stuff you don't want (the delimiters), you capture what you do want (the data).
You can't avoid them showing up in your match results at all, but you can change how they show up and make it more useful for you.
If you change your match pattern to /&something=(.+?)&/ then using your test string of "&something=variable&something_else=var2" the match result array is ["&something=variable&", "variable"]
The first element is always the entire match, but the second one, will be the captured portion from the parentheses, which is much more useful, generally.
I hope this helps.
If you are trying to get variable out of the string, using replace with backreferences will get you what you want:
"&something=variable&something_else=var2".replace(/^.*&something=(.*?)&.*$/, '$1')
gives you
"variable"
I have something like the following;-
<--customMarker>Test1<--/customMarker>
<--customMarker key='myKEY'>Test2<--/customMarker>
<--customMarker>Test3 <--customInnerMarker>Test4<--/customInnerMarker> <--/customMarker>
I need to be able to replace text between the customMarker tags, I tried the following;-
str.replace(/<--customMarker>(.*?)<--\/customMarker>/g, 'item Replaced')
which works ok. I would like to also ignore custom inner tags and not match or replace them with text.
Also I need a separate expression to extract the value of the attribute key='myKEY' from the tag with Text2.
Many thanks
EDIT
actually I am trying to find things between comment tags but the comment tags were not displaying correctly so I had to remove the '!'. There's a unique situation that required comment tags... in anycase if anyone knows enough regex to help, it would be great. thank u.
In the end, I did something like the following (incase anyone else needs this. enjoy!!! But note: Word about town is that using regex with html tags is not ideal, so do your own research and make up your mind. For me, it had to be done this way, mostly bcos i wanted to, but also bcos it simplified the job in this instance);-
var retVal = str.replace(/<--customMarker>(.*?)<--\/customMarker>/g, function(token, match){
//question 1: I would like to also ignore custom inner tags and not match or replace them with text.
//answer:
var replacePattern = /<--customInnerMarker*?(.*?)<--\/customInnerMarker-->/g;
//remove inner tags from match
match = $.trim(match.replace(replacePattern, ''));
//replace and return what is left with a required value
return token.replace(match, objParams[match]);
//question 2: Also I need a separate expression to extract the value of the attribute key='myKEY' from the tag with Text2.
//answer
var attrPattern = /\w+\s*=\s*".*?"/g;
attrMatches = token.match(attrPattern);//returns a list of attributes as name/value pairs in an array
})
Can't you use <customMarker> instead? Then you can just use getElementsByTagName('customMarker') and get the inner text and child elements from it.
A regex merely matches an item. Once you have said match, it is up to you what you do with it. This is part of the problem most people have with using regular expressions, they try and combine the three different steps. The regex match is just the first step.
What you are asking for will not be possible with a single regex. You're going to need a mini state machine if you want to use regular expressions. That is, a logic wrapper around the matches such that it moves through each logical portion.
I would advise you look in the standard api for a prebuilt engine to parse html, rather than rolling your own. If you do need to do so, read the flex manual to get a basic understanding of how regular expressions work, and the state machines you build with them. The best example would be the section on matching multiline c comments.