How do i match text after a specific character? - javascript

I have a url that looks like this:
http://mysite/#/12345
How do I retrieve the text using regex after the /#/ which is essentially a token that I would like to use elsewhere in my javascript application?
Thanks.

You don't need regex here, just String#substr using String#indexOf:
var s = 'http://mysite/#/12345';
var p ='/#/'; // search needle
var r= s.substr(s.indexOf(p) + p.length);
//=> 12345

Let the browser do it for you
var parser = document.createElement('a');
parser.href = "http://mysite/#/12345";
alert(parser.hash.substring(2)); //This is just to remove the #/ at the start of the string
JSFiddle: http://jsfiddle.net/gibble/uvhqa4yv/

Try with JavaScript String methods.
var str='http://mysite/#/12345';
alert(str.substring(str.lastIndexOf("/#/")+3));
You can try with String'smatch() method as well that uses regex expression.
Just get the matched group from index 1 that is captured by enclosing inside the parenthesis (...)
var str='http://mysite/#/12345';
alert(str.match(/\/#\/(.*)$/)[1]);

Using the browser to parse the URL and getting the hash would probably be most reliable and would work with any valid URL
var url = 'http://mysite/#/12345';
var ele = document.createElement('a');
ele.href = url;
var result = ele.hash.slice(2);
FIDDLE
or you can just split and pop it
var result = url.split('#/').pop();

Related

Replace the url parameter value using js

I have a URL like below.
something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false
I want to replace the value of parameter showHiddenElements to some new value.
for e.g. exising value in URL -> showHiddenElements=false
I want to change it through JavaScript to -> showHiddenElements=true
Please advise.
Edit:
showHiddenElements may not always be false. And In some cases it may not be available.
Use the URL Object:
const url = new URL('http://something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false');
url.searchParams.delete('showHiddenElements');
url.searchParams.append('showHiddenElements', true);
So you just delete the parameter and update it with the new one (not the most elegant)
Docs here: https://developer.mozilla.org/fr/docs/Web/API/URL
You could use String.replace for that:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
newUrl = url.replace('showHiddenElements=false', 'showHiddenElements=true');
You could also do it fancy and use regex:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
newUrl = url.replace(/showHiddenElements=false$/, 'showHiddenElements=true');
The regex would only match showHiddenElements=false if it's on the end of the URL
To see if it's available you could use regex too:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
// If the url doesn't have a showHiddenElements=__any_word__
if (!url.match(/showHiddenElements=\w+/)) {
url = url + 'showHiddenElements=false';
}
var url = "something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false";
alert("Before: "+url);
url = url.replace("&showHiddenElements=false","&showHiddenElements=true");
alert("After: "+url);
//Console.log clips the end so we can't see the result :(
Maybe something liket this:
var loc = window.location.href;
var newLoc = loc.Replace('showHiddenElements=true', 'showHiddenElements=false')
A JavaScript Regular Expression should help if you are just treating the URL as a string.
var str = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
var res = str.replace(/showHiddenElements/i, 'true');
console.log(res);

how to replace words in string using javascript?

i have a string,
mystr = 'public\uploads\file-1490095922739.jpg';
i want to replace
public\uploads
with " ", so that i just want to extract only file name ie
file-1490095922739.jpg
or like,
\uploads\file-1490095922739.jpg
how can i do this, is there any methods for this in js or can we do it by replace method.
i am performing the following steps,
var imagepath1;
var imagepath = 'public\uploads\file-1490095922739.jpg';
unwantedChar = 'public|uploads';
regExp = new RegExp(unwantedChar , 'gi');
imagepath = imagepath.replace(regExp , '');
imagepath1 = imagepath;
$scope.model.imagepath = imagepath1.replace(/\\/g, "");
please suggest me optimized method.
var input = "public\\uploads\\file-1490095922739.jpg";
var result = input.replace("public\\uploads\\", "");
This is what you're looking for, no need for fancy regexs :). More information about replace can be found here.
Maybe I don't understand the issue - but wouldn't this work?
var mystr = 'public\uploads\file-1490095922739.jpg';
var filename = mystr.replace('public\uploads', '');
If you want to get the part of the string after the last backslash character, you can use this:
var filename = mystr.substr(mystr.lastIndexOf('\\') + 1);
Also note that you need to escape the backslash characters in your test string:
var mystr = 'public\\uploads\\file-1490095922739.jpg';
What about just doing:
var imagepath = 'public\\uploads\\file-1490095922739.jpg';
$scope.model.imagepath = imagepath.replace('public\\uploads\\', '');
instead of using a bunch of unnecessary variables?
This way you're getting the file path, removing public\uploads\ and then setting the file path to $scope.model.imagepath
Note that this will only work if the image file path always matches 'public\uploads\*FILENAME*'.
var url = '/anysource/anypath/myfilename.gif';
var filename = url.slice(url.lastIndexOf('/')+1,url.length);
Search for the last forward slash, and slice the string (+1 because you don't want the slash), with the length of the string to get the filename. This way, you don't have to worry about the path is at all times.

Single regexp to get page URL but exclude port number from a full URL

I'm trying to come up with a regexp to get the page URL from the full URL but exclude a possible port number from it. So far I came up with the following JS:
var res = url.match(/^.*\:\/\/(?:www2?.)?([^?#]+)/i);
if(res)
{
var pageURL = res[1];
console.log(pageURL);
}
If I call it for this:
var url = "http://www.example.com/php/page.php?what=sw#print";
I get the correct answer: example.com/php/page.php
But if I do:
var url = "http://www.example.com:80/php/page.php?what=sw#print";
I need it to return example.com/php/page.php instead of example.com:80/php/page.php.
I can remove it with the second regexp, but I was curious if I could do it with just one (for speed)?
You can modify your regex to this:
/^.*\:\/\/(?:www2?.)?([^/:]+)(?:[^:]*:\d+)?([^?#]+)/i
RegEx Demo
It will return 2 matches:
1: example.com
2: /php/page.php
as match[1] and match[2] respectively for both inputs that you can concatenate.
http://www.example.com/php/page.php?what=sw#print
OR
http://www.example.com:80/php/page.php?what=sw#print
Update: Here are performance results on jsperf.com that shows regex method is fastest is of all.
Keep it simple:
~ node
> "http://www.example.com:3000/php/page.php?what=sw#print".replace(/:\d+/, '');
'http://www.example.com/php/page.php?what=sw#print'
> "http://www.example.com/php/page.php?what=sw#print".replace(/:\d+/, '');
'http://www.example.com/php/page.php?what=sw#print'
Why would you use a regex at all?
EDIT:
As pointed out by #c00000fd: Because document might not be available and document.createElement is very slow compared to RegExp - see:
http://jsperf.com/url-parsing/5
http://jsperf.com/hostname-from-url
Nevertheless I will leave my original answer for reference.
ORIGINAL ANSWER:
Instead you could just use the Anchor element:
Fiddle:
http://jsfiddle.net/12qjqx7n/
JS:
var url = 'http://foo:bar#www.example.com:8080/php/page.php?what=sw#print'
var a = document.createElement('a');
a.href = url;
console.log(a.hash);
console.log(a.host);
console.log(a.hostname);
console.log(a.origin);
console.log(a.password);
console.log(a.pathname);
console.log(a.port);
console.log(a.protocol);
console.log(a.search);
console.log(a.username);
Additional information:
http://www.w3schools.com/jsref/dom_obj_anchor.asp
How about a group for matching the port, if present?
var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.match(/^.*\:\/\/(?:www2?.)?([^?#\/:]+)(\:\d+)?(\/[^?#]+)/i);
if(res)
{
var pageURL = res[1]+res[3];
console.log(res, pageURL);
}
Try
var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.split(/\w+:\/\/+\w+\.|:+\d+|\?.*/).join("");
var url = "http://www.example.com:80/php/page.php?what=sw#print";
var res = url.split(/\w+:\/\/+\w+\.|:+\d+|\?.*/).join("");
document.body.innerText = res;
You could use replace method to modify your original string or Url,
> var url = "http://www.example.com/php/page.php?what=sw#print";
undefined
> var url1 = "http://www.example.com:80/php/page.php?what=sw#print";
undefined
> url.replace(/^.*?:\/\/(?:www2?.)?([^/:]+)(?::\d+)?([^?#]+).*$/g, "$1$2")
'example.com/php/page.php'
> url1.replace(/^.*?:\/\/(?:www2?.)?([^/:]+)(?::\d+)?([^?#]+).*$/g, "$1$2")
'example.com/php/page.php'
DEMO

Extract url from javascript String

I would like to extract the following String :
http://media.zenfs.com/fr_FR/News/AFP/a418cb581c41fd9c36b0d24c054ad4c623bab222.jpg
from this String :
https://s1.yimg.com/bt/api/res/1.2/yqEp3ogcVvfSaDSSIq.Llg--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9NzU7dz0xMzA-/http://media.zenfs.com/fr_FR/News/AFP/a418cb581c41fd9c36b0d24c054ad4c623bab222.jpg
And before, extract, i would like to check if the global String contains more than one time "http" to be sure to extract the jpg only when needed.
How can i do that ?
Extract the data like this:
var myStr = "https://s1.yimg.com/bt/api/res/1.2/yqEp3ogcVvfSaDSSIq.Llg--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9NzU7dz0xMzA-/http://media.zenfs.com/fr_FR/News/AFP/a418cb581c41fd9c36b0d24c054ad4c623bab222.jpg"
var splittedStr = myStr.split("-");
var extractedStr = splittedStr[3].slice(1);
To find out how many "http" is present in the string:
var count = (myStr.match(/http/g)).length;
Hopes it helps
var source = "https://s1.yimg.com/bt/api/res/1.2/yqEp3ogcVvfSaDSSIq.Llg--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9NzU7dz0xMzA-/http://media.zenfs.com/fr_FR/News/AFP/a418cb581c41fd9c36b0d24c054ad4c623bab222.jpg"
var temp = source.replace("https","http").split("http");
var result = 'http'+temp[2];
use split()
var original = "https://s1.yimg.com/bt/api/res/1.2/yqEp3ogcVvfSaDSSIq.Llg--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9NzU7dz0xMzA-/http://media.zenfs.com/fr_FR/News/AFP/a418cb581c41fd9c36b0d24c054ad4c623bab222.jpg";
original = original.split('-/');
alert($(original)[original.length-1]);
your require URL shows in alert dialog
You can use regex :
str.match(/(http?:\/\/.*\.(?:png|jpg))/i)
FIDDLE

Regex javascript + replace

I got few lines like these:
/coc59409.p?id=1218405784092
/acme-made-skinny-lray-orange/5616664.p?id=1218679205878
/incase-campus-brk-gray-pink-berry/7209107.p?id=1218833962192&skuId=7209107
and I need to delete in all of them what come after this ".p?id="
how can I do that?
results :
/coc59409.p?id=
/acme-made-skinny-lray-orange/5616664.p?id=
/incase-campus-brk-gray-pink-berry/7209107.p?id=
=> "/coc59409.p?id=1218405784092".replace(/\?.*$/,"")
>> "/coc59409.p"
You don't need a regular expression here - contextually what you are referring to is the query string of the URL and there are already tools in the DOM with the facility to tokenise this, for example:
var url = '/coc59409.p?id=1218405784092',
a = document.createElement('a');
a.href = url;
console.log( a.pathname ); // '/coc59409.p'
Details about the HTMLAnchorElement can be found here.
You could just split it,
var url = '/acme-made-skinny-lray-orange/5616664.p?id=1218679205878'
var urlArr = url.split('=');
console.log(urlArr[0]+'=');
Hope that helps :)
Take each line and replace id=[THE REST OF THE LINE] with id=.
Like so:
"coc59409.p?id=1218405784092".replace(/id=(.*)$/, 'id=')

Categories

Resources