I have something I am trying to accomplish.
I'd like to take an array built with AJAX/xml.
array[/word0/, /word1/, /word2/]
and put this into a form that could be used in a .match():
result = string.match(array)
I have tried using a for loop and stepping through the array using string.match(array[i]) to no avail.
Is there an easy way to do this?
Edit: You may have a syntax problem. The following is not valid syntax:
array[/word0/, /word1/, /word2/]
Something like this fixes it:
var regexps = [/word0/, /word1/, /word2/];
Original answer:
Javascript RegExps already do this. You're looking for:
var regexp = /word0|word1|word2/;
Assuming your list of matches comes back in the right format, you could achieve this like so:
var words = ["word0", "word1", "word2"];
var regexp = new Regexp(words.join("|"));
str.match(regexp);
http://jsfiddle.net/KALPh/
Your approach was fine. Here's my implementation:
var regexes = [/^def/, /^abc/],
testString = 'abcdef',
numRegexes = regexes.length;
for(var x=0;x<numRegexes;x++) {
alert(regexes[x].test(testString));
}
To initialize your array, use
var array = [/word0/, /word1/, /word2/];
Then you can use
str.match(array[i])
If your problem is the transmission in "AJAX/xml", then you'll need to build the regular expressions client side with new RegExp(somestring) where somestring might for example be "word0" : you can't embed a regex literal in XML.
Related
I have this part of a function which is running perfectly:
if(/https?:\/\/[a-z]{2}w?\.mywebsite\./.test(href)){
if(!firstSerp){
firstSerp = this;
add_prerender(this, href);
}
}
As you can see mywebsite is hard-coded. What I want is to put a variable there instead.
So it would look like this:
var mylink = 'mywebsite';
if(/https?:\/\/[a-z]{2}w?\.+= mylink\./.test(href)){}
One of the users suggested I look at How do you use a variable in a regular expression?
var replace = "regex";
var re = new RegExp(replace,"g");
But I have difficulties understanding how that would apply to my example.
Could you please help me solve this?
Regular expressions are intended to be used to check if an existing string matches a pattern or to find a pattern in an existing string. You cannot use them to build a string.
Instead, you should use string concatenation:
const url = 'http://www.' + mywebsite + '.com';
or a string template:
const url = `http://www.${mywebsite}.com`;
I need to parse a complex URL string to fetch specific values.
From the following URL string:
/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss
I need to extract this result in array format:
['http://any-feed-url-a.com?filter=hot&format=rss', 'http://any-feed-url-b.com?filter=rising&format=rss']
I tried already with this one /url=([^&]+)/ but I can't capture all correctly all the query parameters. And I would like to omit the url=.
RegExr link
Thanks in advance.
This regex works for me: url=([a-z:/.?=-]+&[a-z=]+)
also, you can test this: /http(s)?://([a-z-.?=&])+&/g
const string = '/api/rss/feeds?url=http://any-feed-url.com?filter=hot&format=rss&url=http://any-feed-url.com?filter=latest&format=rss'
const string2 = '/api/rss/feeds?url=http://any-feed-url.com?filter=hot&format=rss&next=parm&url=http://any-feed-url.com?filter=latest&format=rss'
const regex = /url=([a-z:/.?=-]+&[a-z=]+)/g;
const regex2 = /http(s)?:\/\/([a-z-.?=&])+&/g;
console.log(string.match(regex))
console.log(string2.match(regex2))
have you tried to use split method ? instead of using regex.
const urlsArr = "/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss".split("url=");
urlsArr.shift(); // removing first item from array -> "/api/rss/feeds?"
console.log(urlsArr)
)
which is going to return ["/api/rss/feeds?", "http://any-feed-url-a.com?filter=hot&format=rss&", "http://any-feed-url-b.com?filter=rising&format=rss"] then i am dropping first item in array
if possible its better to use something else then regex CoddingHorror: regular-expressions-now-you-have-two-problems
You can matchAll the url's, then map the capture group 1 to an array.
str = '/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss'
arr = [...str.matchAll(/url=(.*?)(?=&url=|$)/g)].map(x => x[1])
console.log(arr)
But matchAll isn't supported by older browsers.
But looping an exec to fill an array works also.
str = '/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss'
re = /url=(.*?)(?=&url=|$)/g;
arr = [];
while (m = re.exec(str)) {
arr.push(m[1]);
}
console.log(arr)
If your input is better-formed in reality than shown in the question and you’re targeting a modern JavaScript environment, there’s URL/URLSearchParams:
const input = '/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot%26format=rss&url=http://any-feed-url-b.com?filter=rising%26format=rss';
const url = new URL(input, 'http://example.com/');
console.log(url.searchParams.getAll('url'));
Notice how & has to be escaped as %26 for it to make sense.
Without this input in a standard form, it’s not clear which rules of URLs are still on the table.
I have a full string consisting of something like this [(data1.1)(data1.2)][(data2.1)(data2.1)]
Ive read you can do something smart with match function and regex. I want two arrays with the data loaded out of the parentheses.. How in earth do i do that? Please use my string as example.
I came up with this abomination:
var array = s.replace(/^\[|\]$/g,'').split('][').map(function(a){
return a.replace(/^\(|\)$/g,'').split(')(')
});
http://jsfiddle.net/8kLhc/
Also if you deliberately save or transmit data like this then you should really have a look at JSON or proper database design.
I wasn't entirely sure what you were after, but I'm assuming this
var what = '[(data1.1)(data1.2)][(data2.1)(data2.2)]',
have = [],
you = [],
tried = /\[\(([^)]*)\)\(([^)]*)\)\]/g;
what.replace(tried, function (use, brain, forthis) {
you.push((have.push(brain), forthis));
});
console.log(have, you);
// ["data1.1", "data2.1"] ["data1.2", "data2.2"]
just felt like asking this as there are always jewels popping up on stackoverflow :)
What I have is the following list:
list1 = [['command','arg1','arg2'], ['command2','arg1'], ... ]
How would you recommend to transform it into a string in order to be passed as ONE GET argument?
e.g.
http://webgame_site.com/command_list/?data=...
What I am currently doing is separating lists using commas , ; , but I don't like this idea as the method would break if I decide to introduce these within strings.
I'm trying to be as compact as possible.
One idea I've had is to encode the list into base64:
[['command','arg1','arg2'], ['command2','arg1']]
=> "W1snY29tbWFuZCcsJ2FyZzEnLCdhcmcyJ10sWydjb21tYW5kMicsJ2FyZzEnXV0="
which is shorter than URIencode
Any ideas? :)
Convert it to json then encode the characters using encodeURI.
var list1 = [['command','arg1','arg2'], ['command2','arg1']];
var encoded = encodeURI(JSON.stringify(list1));
alert(encoded);
Edit for base64:
var list1 = [['command','arg1','arg2'], ['command2','arg1']];
var encoded = btoa(JSON.stringify(list1));
alert(encoded);
alert(atob(encoded));
jQuery.param() sounds good.
Good morning
is there a clever way to use a javascript regular expression to clean up this string:
var spans = "<SPAN><IMG src="remove.gif" width=18> Mirage - JOY</SPAN>
<SPAN><IMG src="remove.gif" width=18> Nikon - D40 </SPAN>
<SPAN><IMG src="remove.gif" width=18> Mitsuca - DS 6083 </SPAN>"
and produce a resulting array like this:
var filtered = ["12372","12427","12438"];
the source html string in spans variable could be indented or not.
thanks in advance
I'd suggest matching just the script portion. Something like this:
regex = /RemoveProductFromSelection\('(\d+)'\)/g;
while (match = regex.exec(spans)) {
console.dir(match);
}
note: I've used console.dir() here to output the results in an easy to read format. console.dir() is a debugging function in Firebug; if you're not using Firebug, you'll need to use a different method to see the results.
Hey Spudley, here is what I've got so far
var filtered= spans.match(/\('(\d+)'\)/g);
for (var k=0;k<filtered.length;k++){
filtered[k] = filtered[k].match(/\d+/g);
alert(filtered[k]);
}