Regular Expression Error with Match() Method - javascript

I am using a regular expression to capture a URL string, but it's not working out.
Here's my code, which is coming from an external JavaScript document, linked to the HTML file:
var url = 'The URL was www.google.com';
var urlRegEx = /((\bhttps?:\/\/)|(\bwww\.))\S*/;
var urlRegMatch = url.match(urlRegEx);
document.write(urlRegMatch);
The output that I get is this: "www.google.com,www.,,www."
What am I doing wrong?
Thanks! :)

Your regex works fine, what happens is that according to the match function you are getting one extra result for each group (defined by these parenthesis) that you have in your regex. to access the whole match you can access to the first item of the match return like the following:
var url = 'The URL was www.google.com';
var urlRegEx = /((\bhttps?:\/\/)|(\bwww\.))\S*/;
var urlRegMatch = url.match(urlRegEx)[0]; //this line changed, im using [0] to access the whole match only
document.write(urlRegMatch);
working example: https://jsfiddle.net/2sptg5rz/3/
reference about the match function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match#Return_value

I'd like to thank #Dknacht and #Tressa for directing me to the correct answer, since the first value of the array, 0, is the matched text.
This code works for what I want to do:
var url = 'The URL was www.google.com';
var urlRegEx = /((\bhttps?:\/\/)|(\bwww\.))\S*/
var urlRegMatch = url.match(urlRegEx);
document.write(urlRegMatch[0]);

Related

How to add a variable to a regex checking for a URL?

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`;

How do I replace characters using Javascript in HTML file?

For example I have a string getting from current URL using javascript
hostname/report/searchDate?searchOrderID=&searchDateFrom=2018-10-16&searchDateTo=2018-10-23&search=search&sortBy=OrderDateAsc
How do I replace character in the end OrderDateAsc ? If I want to replace for example , OrderDateDesc , how should I do it using Javascript ? The URL infront might be differs all the time , they keyword should be &sortBy.
Please help ,thanks.
var currentUrl = window.location.href;
var url = new URL(currentUrl);
var c = url.searchParams.get("sortBy");
You can get sortBy value like this, and maybe you can use some if statements for if set or not , and you can set like this:
url.searchParams.set('sortBy',"WhateverYouWant");
Also,convert url to string, you can read parameters url.searchParams.get("sortBy"); and again some if statements,
if change :
url = url.Replace(sortByValue,"WhateverYouWant");
this will works too.
But if your string looks like that and you try to change search value, then you will change every "search" value and its not work. :
hostname/report/searchDate?searchOrderID=&searchDateFrom=2018-10-16&searchDateTo=2018-10-23&search=search&sortBy=OrderDateAsc
change search as WhateverYouWant
hostname/report/WhateverYouWantDate?WhateverYouWantOrderID=&WhateverYouWantDateFrom=2018-10-16&WhateverYouWantDateTo=2018-10-23&WhateverYouWant=WhateverYouWant&sortBy=OrderDateAsc
You see, its bad :)
You could do it with the following code.
//your string
let str = "hostname/report/searchDate?searchOrderID=&searchDateFrom=2018-10-16&searchDateTo=2018-10-23&search=search&sortBy=OrderDateAsc";
//find "OrderDateAsc" and replace it with "OrderDateDesc"
str = str.replace("OrderDateAsc", "OrderDateDesc" );
you can use regular expression and replace the sortBy param value like that:
const url ='hostname/report/searchDate?searchOrderID=&searchDateFrom=2018-10-16&searchDateTo=2018-10-23&search=search&sortBy=OrderDateAsc';
const regex = /(&sortBy=OrderDate)(Asc)/gi;
const newUrl = url.replace(regex, '$1Desc');

jQuery regex match returning empty string

I need to strip out the IDs of embedded youtube videos, so I have the url which is something like:
www.youtube.com/embed/[someID]&rel=0&controls=0&showinfo=0&frameborder=1&modestbranding=1
All I want is the [someID] string. I have declared an empty array to store the regex matches;
var videoID = [];
The closest I have come to a solution is:
videoID = videoID.match("embed/(\w*)");
but this results in the following:
video[0] ("embed/")
video[1] ()
Use this:
url = "www.youtube.com/embed/someID&rel=0&controls=0&showinfo=0&frameborder=1&modestbranding=1";
Then use either:
var videoID = url.match(/embed\/(\w*)/); // regex
OR else:
var videoID = url.match("embed/\\w*)"); // regex object
Both will give this output:
["embed/someID", "someID"]
If you provide a string then String#match method will attempt to construct a RegExp object and for that case you need to use \\w instead of \w.
Try this you may get id. I didn't use regex but still we can get id from above demo like urls.
var url ="www.youtube.com/embed/[someID]&rel=0&controls=0&showinfo=0&frameborder=1&modestbranding=1";
var urlQueries = url.split('/');
var queryParameters = urlQueries[2].split('&'); // arrays of all query parameters
var id = queryParameters[0]; // get ids at index 0
Working demo here
I'm not sure if jquery can do Positive-Lookbehinds, but try this (?<=embed\/)([^&]*)
If not, then (?:embed\/)([^&]*) is closer to your example.
Demo:
http://regex101.com/r/nW5uL8

JS Regex match string with $

I am trying to write something that would look at tweets and pull up info about stocks being mentioned in the tweet. People use $ to reference stock symbols on twitter but I cant escape the $.
I also dont want to match any price mention or anything like that so basically match $AAPL and not $1500
I was thinking it would be something like this
\b\$[a-zA-Z].*\b
if there are multiple matches id like to loop through them somehow so something like
while ((tweet = reg.exec(sym_pat)) !== null) {
//replace text with stock data.
}
This expression gives me an unexpected illegal token error
var symbol_pat = new RegExp(\b\$[a-z]*);
Thanks for the help if you want to see the next issue I ran into
Javascript AJAX scope inside of $.each Scope
Okay, you've stated that you want to replace the matches with their actual stock values. So, you need to get all of the matching elements (stock ticker names) and then for each match you're going to replace the it with the stock value.
The answer will "read" very similarly to that sentence.
Assume there's a tweet variable that is the contents of a particular tweet you're going to work on:
tweet.match(/\b\$[A-Za-z]+\b/g).forEach(function(match) {
// match looks like '$AAPL'
var tickerValue = lookUpTickerValue(match);
tweet.replace(match, tickerValue);
});
This is assuming you have some logic somewhere that will grab the ticker value for the given stock name and then replace it (it should probably return the original value if it can't find a match, so you don't mangle lovely tweets like "Barbara Streisand is $ATAN").
var symbol_pat = new RegExp('\\b\\$[a-z]+\\b','gi');
// or
var symbol_pat = /\b\$[a-z]+\b/gi;
Also, for some reason JS can not calculate the beginning of a word by \b, it just catches the one at the end.
EDIT: If you're replacing the stock symbols you can use the basic replace method by a function and replace that data with predefined values:
var symbol_pat = /(^|\s)(\$[a-z]+\b)/gi;
var stocks = {AAPL:1,ETC:2}
var str = '$aapl ssd $a a$s$etc $etc';
console.log(str);
str = str.replace(symbol_pat, function() {
var stk = arguments[2].substr(1).toUpperCase();
// assuming you want to replace $etc as well as $ETC by using
// the .toUpperCase() method
if (!stocks[stk]) return arguments[0];
return arguments[0].replace(arguments[2],stocks[stk]);
});
console.log(str);

How to convert jquery attr value to a string object to use it as a regex expression?

i want to search a string variable if it contains a jQuery object's attr value. I have tryed this:
var txt = "lets go to a.html";
var searchText = new RegExp($("#link").attr("href"));
alert(txt.search(searchText)>=0);
but this always returns false.
im sure that $("#link").attr("href") returns "a.html" as value.
also i have tried this if i was doing something wrong,
var txt = "lets go to a.html";
var searchText = new RegExp("a.html");
alert(txt.search(searchText)>=0);
this time it has returned true.
i thought jquery was not returning a string object and i have tried to turn it to string like this:
var txt = "lets go to a.html";
var searchText = new String($("#link").attr("href"));
searchText = new RegExp(searchText);
alert(txt.search(searchText)>=0);
this has aslo returned false..
when i used toString($("#link").attr("href")) it always returns true even attr value is not "a.html"
anyone can help me on this?
thank you.
Do this:
var txt = "lets go to a.html";
var searchText = $("#link").attr("href");
alert(txt.indexOf(searchText) !== -1);
To create a regular expression from a string:
var re = new RegExp('your string');
To see if it matches another string:
re.test('another string'); // false
re.test('here is your string'); // true
Note though that some characters must be escaped, so to match a whitespace:
var re = new RegExp('\\s');
In your case, you should reverse the sense of the test:
searchText.test(txt)
which will return true if 'a.html' is in txt.
Depending on what browser you are testing in the href attribute, when queried through jQuery, will return a fully qualified url even tho you have set it to a relative url.
Test to make sure that $('#link').attr('href') actually returns a.html and not http://url/a.html.
Okay problem is solved i must say sorry to everyone who spent time to solve this problem
problem was on my html :(
i have putted an emty character inside the href attribute like this:
<a href="a.html ">
the codes i have given all are working well :)

Categories