Display page name in javascript? - javascript

How would I add location.href.split('/').pop() to a html document to display the page name? (not the whole URL) I would like to display the page name ONLY.
example:
if the page was "www.example.com/whaterver/mypage.html"
it would display "mypage".
What would be the full script? I am new to javascript and I found this online but I don't know the whole code. could anyone help me out?

I would stick it in a function in case you need to reuse it elsewhere in your code. Just split the page name at the end and take the first element:
function getPageName(url) {
return url.split('/').pop().split('.')[0];
}
You can pass in the actual URL:
var pageName = getPageName('www.example.com/whaterver/mypage.html'); // mypage
Or, using location.href:
var pageName = getPageName(location.href); // mypage
I might also be inclined to return something if there is no match for *.html, so here's a revised function that returns null if there isn't a match:
function getPageName(url) {
var pageName = url.split('/').pop().split('.')[0];
return pageName.length > 0 ? pageName : null;
}
DEMO

Note: If you do .split('.') like other solutions instruct, you will miss the base names from many URLs.
You can find the last forward slash and search ahead for the first ., ?, & or # to catch variations of URLs. This is the equivalent of PHP's basename
function getBaseName(url) {
if(!url || (url && url.length === 0)) {
return "";
}
var index = url.lastIndexOf("/") + 1;
var filenameWithExtension = url.substr(index);
var basename = filenameWithExtension.split(/[.?&#]+/)[0];
// Handle '/mypage/' type paths
if(basename.length === 0) {
url = url.substr(0,index-1);
basename = getBaseName(url);
}
return basename ? basename : "";
}
and use it like so
var url = "http://www.example.com/whaterver/mypage.html";
var file = getBaseName(url);
of
var file = getBaseName(location.pathname); // The current script page
Results:
http://www.example.com/whaterver/mypage/ => "mypage"
http://www.example.com/whaterver/mypage.html => "mypage"
http://www.example.com/whaterver/mypage => "mypage"
http://www.example.com/whaterver/mypage/ => "mypage"
http://www.example.com/whaterver/mypage#works => "mypage"
http://www.example.com/whaterver/mypage?ver=1 => "mypage"
JSBin Demo

Related

How to extract the content of the first paragraph in html string react native

I am working on a react native project and I have an html string json api response.
I am using react-native-render-html to render it, and I can get all paragraphs and apply specific things like number of lines ,etc.. . However I want to get only the first paragraph in the response.
str response='<p>text1</p> <p>text2</p> <p>text3</p>';
Is it possible to write a regular expression to get only the content of first paragraph which is for example text1 ?
I don't use React Native but in javascript you could do something like that:
const paragraphs = response.split("</p>")
const firstParagraph = paragraphs[0]+'</p>';
Or with a regex you can do something like that:
// extract all paragraphe from the string
const matches = [];
response.replace(/<p>(.*?)<\/p>/g, function () {
//use arguments[0] if you need to keep <p></p> html tags
matches.push(arguments[1]);
});
// get first paragraph
const firstParagraph = (matches.length) ? matches[0] : ""
Or like that (I think it is the best way in your case)
const response='<p>text1</p> <p>text2</p> <p>text3</p>';
const regex = /<p>(.*?)<\/p>/;
const corresp = regex.exec(response);
const firstParagraph = (corresp) ? corresp[0] : "" // <p>text1</p>
const firstParagraphWithoutHtml = (corresp) ? corresp[1] : "" // text1
Hope it will help
var response='<p>text1</p> <p>text2</p> <p>text3</p>';
var firstParagraphElement=response.split("</p>")[0] //firstparagraphElement="<p>text1"
var paragraphContent=firstParagraphElement.replace("<p>","") //paragraphContent="text1"
javascript split() function reference click
javascript replace() function reference click
In React Native you can also use parse5 to extract a string from HTML code. I have used this code in a project for doing so:
import parse5 from 'parse5'
const isText = (tagName): Boolean => tagName === '#text'
const processNode = (node): String => {
const nodeName = node.nodeName
if (isText(nodeName)) {
return node.value
}
if (!node.childNodes) {
return ''
}
return node.childNodes.map((child, index) => processNode(child)).join(' ')
}
export const htmlToText = (html): String => {
const root = parse5.parseFragment(html)
return processNode(root).replace(/\s+/g, ' ').trim()
}
Here is a simple JEST test for the function above:
test('when full document htmlToText should get text', () => {
const htmlToText1 = htmlToText("<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>")
expect(htmlToText1)
.toBe(`titleTest test01 test02 test03`);
});

How to call a function with href to other page on HTML

So I have 3 links: 1, 2 and 3 and they all go to the same page and each have a function (1(), 2() and 3()) I want to, when you go to one of those pages from the home page, to go to the 123.html and run 1() or 2() depending on what button they clicked.
I've tried this:
<li><span>Link1</span></li>
But it didn't run the function at all. And I want to have all of them like this:
<li><span>Link1</span></li>
<li><span>Link2</span></li>
<li><span>Link3</span></li>
You cannot pass javascript to a page like this unless the page you are going to is looking for the javascript query string in the url.
It would be better to send a query string variable such as ?action=Link1 and then have some javascript check for the "action". You could then run a function based on what the action is.
There are a lot of functions you can find that will do this for you, by looking at the window.location variable
This is not the way of doing.
What you could do is add a parameter in your link, something like
?function:1.
You can then extract the parameter on your 123.html page like this :
var url_string = window.location.href
var url = new URL(url_string)
var c = url.searchParams.get("function")
c will have the value of 1, 2 or 3. With that you can make a switch statement and select which function to execute :
switch(c) {
case 1:
function1()
break
}
I do not recommend working like this but if you want to do it like that here you go.
Based on a similar question you can't (1st answer), but expanding on this answer you can do something like this
a.html
<li><span>Link1</span></li>
b.html
<script>
// get hash from url
var hash = window.location.hash;
// clean
hash = hash.replace('#', '');
hash = hash.replace(';', '');
hash = hash.replace(new RegExp("%20", "g"), "");
const fb = (a, b) => {
console.log(a);
console.log(b);
}
// Option 1:
/**
* parse all parameters from string to an array
*/
const parseParams = (str) => {
let params = str.split(/[/(/)]/)[1].split(',');
for (i=0; i < params.length; i++) {
params[i] = params[i].replace(new RegExp("'", "g"), "");
}
return params;
}
// check for existing function - parse only the function name
switch(hash.substring(0, hash.indexOf("("))) {
case "fb":
var params = parseParams(hash);
fb(...params);
break;
default:
break
}
// Option 2 (easy solution but try to avoid this):
eval(hash);
</script>

how to determine whether that extension is for an audio type?

In JavaScript, I have a string contain filename + ext like: var s = "blabla.mp3".
How to find out if the string contain file ext that matches for audio type?
mp3, mp4....
var s = 'blabla.mp3';
function isAudioType(s) { return true/false; }
You can using regex:
function isAudioType(s) {
return /\.(mp3|mp4)$/i.test(s);
}
Use a function which matches the target file name's extension against a list of desired extensions you want to check.
function isAudioType(s) {
var audioTypes = [".mp3", ".wav"], // Add as many extensions you like here...
audioExt = s.replace(/^.+(?=\.)/i, '');
return (audioTypes.indexOf(audioExt.toLowerCase()) > -1);
}
console.log(isAudioType('blabla.mp3'));
console.log(isAudioType('blabla.jpg'));
With this code you can add as many cases as you want. In this example I added the mp3 case only. You could add mp4 and others too, using a switch for example.
var s = 'blabla.mp3';
function isAudio (fileName) {
let arr = fileName.split('.');
if (arr[arr.length-1] === 'mp3'){
return true;
}
}
console.log(isAudio(s));

JSON route matching via regex

Consider I have following JSON object
var urls = {
"GET/users/:id":1,
"POST/users":0
}
and if I have string "GET/users/10". How can I use this as key to get the value from urls JSON i.e. "GET/users/10" should match "GET/users/:id".
I don't want to iterate urls JSON and use regex for every key.
Is there a way to access JSON object using regex?
Thanks in advance.
Here is something that should work for you. I took some of the pieces from the Durandal router's RegEx matching logic which basically dynamically creates a regular expression object based on a defined route string and then tests with it against a passed string.
Here is the working example:
var urls = {
"GET/users/:id": 1,
"POST/users": 0
}
const getRouteRegExp = (
routeString,
routesAreCaseSensitive = false,
optionalParam = /\((.*?)\)/g,
namedParam = /(\(\?)?:\w+/g,
splatParam = /\*\w+/g,
escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g
) => {
routeString = routeString.replace(escapeRegExp, '\\$&')
.replace(optionalParam, '(?:$1)?')
.replace(namedParam, function(match, optional) {
return optional ? match : '([^\/]+)';
})
.replace(splatParam, '(.*?)');
return new RegExp('^' + routeString + '$', routesAreCaseSensitive ? undefined : 'i');
}
const getRouteByString = (string) => {
var resultArr = Object.entries(urls).find(([k, v]) => {
var regEx = getRouteRegExp(k)
return regEx.test(string)
}) || []
return resultArr[0]
}
console.log(getRouteByString('GET/users/10'))
console.log(getRouteByString('POST/users'))
console.log(getRouteByString('POST/users2'))
So what you have is the getRouteRegExp function which is the main thing here which would compose a regular expression object based on a passed route.
After that we go and for each existing route defined in urls we create one RegExp and try to match it against the provided string route. This is what the find does. If one is found we return it.
Since we are doing Object.entries we return the 0 index which contains the result.
Since this comes straight from the Durandal bits it supports all the route expressions that are built in Durandal ... like:
Static route: tickets
Parameterized: tickets/:id
Optional Parameter: users(/:id)
Splat Route: settings*details
You can read more about Durandal Router here
From your question what I can understand is your key is dynamic, so you can do something like this:
var urls = {
"GET/users/:id":1,
"POST/users":0
}
let id = 10
const yourValue = urls["GET/users/" + id]
You can use this code to
var urls = {
"GET/users/:id":1,
"POST/users":0
}
var regex = /"([^"]+?)"\s*/g;
var urlsJson = JSON.stringify(urls);
let result = regex.exec(urlsJson)
if(result && result.length > 0) {
var keyJson = result[1];
var value = urls[keyJson]
console.log('value', value)
}
Try Something like this:
const urls = (id) => ({
[`GET/users/${id}`]:1,
"POST/users":0,
});
console.log(urls(2));
I hope it may be helpful.
The json would look fine, just do a replace on the url, so replace the ending integer with :id and then you have the key by which you can directly access the value in the json.
So:
var url = "GET/users/10";
var urls = {
"GET/users/:id":1,
"POST/users":0
}
url = url.replace(/users\/\d+/, 'users/:id');
console.log(urls[url]);
Do as many replaces on the url to convert all possible url's to the keys in your json.

How do I get query string value from script path?

I am adding my Javsacript file in pages with different query strings in the script path like this:
Page1:
<script type="text/javascript" src="file.js?abc=123"></script>
Page2:
<script type="text/javascript" src="file.js?abc=456"></script>
Page3:
<script type="text/javascript" src="file.js?abc=789"></script>
In my Javascript file, how can I get the value of the "abc" param? I tried using window.location for this, but that does not work.
In case it helps, below is a function I use to find the value of a query string param:
function getQuerystring(key, defaultValue) {
if (defaultValue == null) defaultValue = "";
key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
var qs = regex.exec(window.location.href);
if (qs == null)
return defaultValue;
else
return qs[1];
}
This is possible. See Passing JavaScript arguments via the src attribute. The punchline is that since scripts in HTML (not XHTML) are executed as loaded, this will allow a script to find itself as it is always the last script in the page when it’s triggered–
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
// myScript now contains our script object
var queryString = myScript.src.replace(/^[^\?]+\??/,'');
Then you just apply the query string parsing.
First, the technical answer: if you assign your script tag an ID, you can then grab its src and then parse out the query string.
<script id="whatever" type="text/javascript" src="file.js?abc=123"></script>
var path = document.getElementById('whatever').src;
// ...
With that answered, I'd like to voice my concern — this reeks of poor design decisions. Why are you including your script this way (with a querystring)? If you're trying to optimize your site (by having one large script that can be cached for subsequent pages), this approch is actually counter-productive because browsers will make a fresh request for the script file on each page due to the differing query string. The correct approach is to have one large shared file and then a small page-specific file on each page.
Since there is no more significant use of Internet Explorer. You can use document.currentScript and new URL, which return a string with the tag <script> in question.
const search = new URL(document.currentScript.src).search.substring(1)
const stringPreparation = decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')
const qs = JSON.parse('{"' + stringPreparation + '"}')
You can reduce this code to one line, but it is not recommended, let minifier scripts do that.
You can use the URL api and document.currentScript to retreive this`
const url = new URL(document.currentScript.getAttribute('src'));
const scriptParams = Object.fromEntries(url.searchParams)
console.log(scriptParams);
I have a quick and easy solution for extracting the query string from a js file using jQuery to grab the script tag source attribute and simply using two separate functions for parsing the JS file path and query string. Obviously, jQuery is required.
$(document).ready(function() {
var p = parseURL($('script[src*="thisfile.js"]').attr('src'));
console.log(p);
});
// Parse a URL into its parts
function parseURL(url)
{
var p = document.createElement('a');
p.href = url;
var obj = {
'protocol' : p.protocol,
'hostname' : p.hostname,
'port' : p.port,
'pathname' : p.pathname,
'search' : p.search,
'query' : p.search.substring(1),
'args' : parseStr(p.search.substring(1)),
'hash' : p.hash,
'host' : p.host
};
return obj;
}
// Parse a query string
function parseStr(string)
{
var args = string.split('&');
var argsParsed = {};
for (i = 0; i < args.length; i++)
{
var arg = decodeURIComponent(args[i]);
if (arg.indexOf('=') == -1)
{
argsParsed[arg.trim()] = true;
}
else
{
var kvp = arg.split('=');
argsParsed[kvp[0].trim()] = kvp[1].trim();
}
}
return argsParsed;
}

Categories

Resources