Get string from a successful regex? - javascript

I'm trying to manipulate a string that has tested as a positive match against my regex statement.
My regex statement is /\[table=\d](.*?)\[\/table] / gmi and an example of a positive match would be [table=1]Cell 1[c]Cell 2[/table]. I'm searching for matches within a certain div, which I'll call .foo in the code below.
However, once the search comes back saying it has found a match, I want to have the section that was identified as a match returned back to me so that I can start manipulating a specific section of it, namely count the number of times [c] appears and reference the number in [table=1].
(function(regexCheck) {
var regex = /\[table=\d](.*?)\[\/table] / gmi;
$('.foo').each(function() {
var html = $(this).html();
var change = false;
while (regex[0].test(html)) {
change = true;
//Somehow return string?
}
});
})(jQuery);
I'm quite new to javascript and especially new to RegEx, so I apologise if this code is crude.
Thanks for all of your help in advance.

Use exec instead of test and keep the resulting match object:
var match;
while ((match = regex[0].exec(html)) != null) {
change = true;
// use `match[0]` for the full match, or `match[1]` and onward for capture groups
}
Simple example (since your snippet isn't runnable, I've just created a simple one instead):
var str = "test 1 test 2 test 3";
var regex = /test (\d)/g;
var match;
while ((match = regex.exec(str)) !== null) {
console.log("match = " + JSON.stringify(match));
}

Related

Match Regex if not inside specific HTML tag

I would like to get special formatted strings ({string}) out of the HTML which are not inside a specific HTML tag.
For example I would like to match {test} and not <var>{test}</var>.
Therefore I am using the following regex: (excluding is done with ?!)
(?!<var>)\{\S+?\}(?!<\/var>)
So this works very well for texts with spaces, but if I have something like (where there is no space in-between):
<var>{name}</var>{username}
it matches two {}-strings: {name}</var>{username}
How can I just match {username} here?
Update:
If I need to do something like this
<var.*?<\/var>|(\{\S+?\})
How can I get the matched values, because the matched index depends on the position.
Examples:
Match 1:
"{username}<var>{name}</var>".match(/<var.*?<\/var>|(\{\S+?\})/g);
=> ["{username}", "<var>{name}</var>"]
Match 2:
"<var>{name}</var>{username}".match(/<var.*?<\/var>|(\{\S+?\})/g);
=> ["<var>{name}</var>", "{username}"]
Current Solution:
angular.forEach(html.match(regex), function (match) {
if(match.substring(0, 4) !== '<var') {
newAdded = match;
}
});
Is this really the 'best' solution for JavaScript?
Here is how you can achieve this using the following regex:
/<var.*?<\/var>|(\{\S+?\})/g;
var s = '<var>{name}</var>{username}<var>{newname}</var>{another_username}';
var log = [];
var m;
var regex = /<var.*?<\/var>|(\{\S+?\})/g;
while ((m = regex.exec(s)) !== null) {
if ( m[1] !== undefined) {
log.push(m[1]);
}
}
alert(log);

Keeping only part of a regex match

I need to search for a word in text. For this I used this regex:
var re =/duration='\d+'/ig;
var i = text.match(re);
This gives me an array of matches like "duration='300'", "duration='400'",...
I need to get only numbers. without duration=''
You can use a capturing group:
var re = /duration='(\d+)'/ig;
var match = re.exec(text);
while (match != null) {
// matched text: match[1]
match = re.exec(text);
}
Tim's answer works well (and I'm not sure why the OP says it is not what he/she wants). That said, here is another way to do it using the String.replace() method with a callback function replacement value:
function getDurations(text) {
var re =/duration='(\d+)'/ig;
var i = [];
text.replace(re, function(m0, m1){i.push(m1); return '';});
return i;
}
Note that this technique requires no loop and is quite efficient getting the job done in a single statement.

Remove special character from the starting of a string and search # symbol.in javascript

I want to remove special characters from the starting of the string only.
i.e, if my string is like {abc#xyz.com then I want to remove the { from the starting. The string shoould look like abc#xyz.com
But if my string is like abc{#xyz.com then I want to retain the same string as it is ie., abc{#xyz.com.
Also I want to check that if my string has # symbol present or not. If it is present then OK else show a message.
The following demonstrates what you specified (or it's close):
var pat = /^[^a-z0-9]*([a-z0-9].*?#.*?$)/i; //pattern for optional non-alphabetic start followed by alphabetic, followed by '#' somewhere
var testString = "{abc#xyz.com"; //Try with {abcxyz.com for alert
arr = pat.exec(testString);
var adjustedString;
if (arr != null) { adjustedString = arr[1]; } //The potentially adjustedString (chopped off non-alphabetic start) will be in capture group 1
else { adjustedString = ""; alert(testString + " does not conform to pattern"); }
adjustedString;
I have used two separate regex objects to achieve what you require .It checks for both the conditions in the string.I know its not very efficient but it will serve your purpose.
var regex = new RegExp(/(^{)/);
var regex1 = new RegExp(/(^[^#]*$)/);
var str = "abc#gmail.com";
if(!regex1.test(str)){
if(regex.test(str))
alert("Bracket found at the beginning")
else
alert("Bracket not found at the beginning")
}
else{
alert("doesnt contain #");
}
Hope this helps

Javascript Regex (replace) Issue

I am checking a collection and replacing all
<Localisation container="test">To translate</Localisation>
tags with text.
The next codes does what I want:
var localisationRegex = new RegExp("(?:<|<)(?:LocalisationKey|locale).+?(?:container|cont)=[\\\\]?(?:['\"]|("))(.+?)[\\\\]?(?:['\"]|(")).*?(?:>|>)(.*?)(?:<|<)/(?:LocalisationKey|locale)(?:>|>)", "ig");
match = localisationRegex.exec(parsedData);
while (match != null) {
var localeLength = match[0].length;
var value = match[4];
parsedData = parsedData.substr(0, match.index) + this.GetLocaleValue(value) + parsedData.substr(match.index + localeLength);
match = localisationRegex.exec(parsedData);
}
But, when the the string I replace with, Is longer then the original string, the index/place where it will start to search for the next match, is wrong (to far). This sometimes leads to tags not found.
Setting aside the (important) question as to whether the approach is a good one, if it were me I'd avoid the problem of indexing through the source text by using a function argument to the regex:
var localizer = this;
var result = parsedData.replace(localisationRegex, function(_, value) {
return localizer.GetLocaleValue(value);
});
That will replace the tags with the localized content.

Why does this jQuery code not work?

Why doesn't the following jQuery code work?
$(function() {
var regex = /\?fb=[0-9]+/g;
var input = window.location.href;
var scrape = input.match(regex); // returns ?fb=4
var numeral = /\?fb=/g;
scrape.replace(numeral,'');
alert(scrape); // Should alert the number?
});
Basically I have a link like this:
http://foo.com/?fb=4
How do I first locate the ?fb=4 and then retrieve the number only?
Consider using the following code instead:
$(function() {
var matches = window.location.href.match(/\?fb=([0-9]+)/i);
if (matches) {
var number = matches[1];
alert(number); // will alert 4!
}
});
Test an example of it here: http://jsfiddle.net/GLAXS/
The regular expression is only slightly modified from what you provided. The global flag was removed, as you're not going to have multiple fb='s to match (otherwise your URL will be invalid!). The case insensitive flag flag was added to match FB= as well as fb=.
The number is wrapped in curly brackets to denote a capturing group which is the magic which allows us to use match.
If match matches the regular expression we specify, it'll return the matched string in the first array element. The remaining elements contain the value of each capturing group we define.
In our running example, the string "?fb=4" is matched and so is the first value of the returned array. The only capturing group we have defined is the number matcher; which is why 4 is contained in the second element.
If you all you need is to grab the value of fb, just use capturing parenthesis:
var regex = /\?fb=([0-9]+)/g;
var input = window.location.href;
var tokens = regex.exec(input);
if (tokens) { // there's a match
alert(tokens[1]); // grab first captured token
}
So, you want to feed a querystring and then get its value based on parameters?
I had had half a mind to offer Get query string values in JavaScript.
But then I saw a small kid abusing a much respectful Stack Overflow answer.
// Revised, cooler.
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(window.location.search);
return match ?
decodeURIComponent(match[1].replace(/\+/g, ' '))
: null;
}
And while you are at it, just call the function like this.
getParameterByName("fb")
How about using the following function to read the query string parameter in JavaScript:
function getQuerystring(key, default_) {
if (default_==null)
default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
and then:
alert(getQuerystring('fb'));
If you are new to Regex, why not try Program that illustrates the ins and outs of Regular Expressions

Categories