jQuery append end of url? - javascript

I have a url variable http://blah.com/blah/blah/blah and I have another url http://shop.blah.com/ I want to take the first url (blah.com) and add the ending blah/blah/blah to the second url http://shop.blah.com
So I end up with http://shop.blah.com/blah/blah/blah
Any idea of how I could do this?

var url1 = 'http://blah.com/blah/blah/blah';
var url2 = 'http://shop.blah.com/';
var newUrl = url2 + url1.replace(/^.+?\..+?\//, '');

It sounds like the jQuery-URL-Parser plugin might come in handy here:
var url = $.url(); //retrieves current url
You can also get specific parts of the URL like this:
var file = $.url.attr("file");
var path = $.url.attr("path");
var host = $.url.attr("host");
...
If you need to get Querystring parameters:
var parm = $.url.param("id");

If the intent is just to add shop to the front of the domain name:
var url2 = url1.replace('://', '://shop.');

<script>
$(document).ready(function(){
//this uses the browser to create an anchor
var blah = document.createElement("a");
//initialize the anchor (all parts of the href are now initialized)
blah.href = "http://blah.com/blah/blah/blah?moreBlah=helloWorld#hashMark";
var shop = document.createElement("a");
//initialize the anchor (all parts of the href are now initialized)
shop.href = "http://shop.blah.com/";
shop.pathname = blah.pathname; //the blahs
shop.search = blah.search; //the blah query
shop.hash = blah.hash; // the blah hashMark
alert("These are the droids you're looking for: "+shop.href);
});
</script>

Related

Change (or add) id name using url parameters

I need to change or create a div from an url parameters
<div class="myclass"></div>
www.example.com?change=newdiv
<div class="myclass" id="newdiv"></div>
Is it possible to do this with js?
yes you can do it like that :) :
var url_string = window.location.href; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("change");
var element = document.getElementsByClassName("myclass");
element[0].setAttribute("id",c);
Basically you need to create new URL property using https, otherwise you will get a
TypeError: www.example.com is not a valid URL.
After that get the search parameter change and create a div where to set the id
const url = new URL('https://www.example.com?change=newdiv');
const changeParamValue = url.searchParams.get("change");
console.log("param value: " + changeParamValue)
let newDiv = document.createElement("div");
newDiv.setAttribute("id", changeParamValue);
console.log(newDiv)

Merge duplicate URLs into 1 URL, Javascript

I have function, which shows / outputs the urls from the textarea. At the moment however it won't merge duplicates into 1 URL. How can I output same urls as one (Merge http://google.com, www.google.com, http://www.google.com, or just google.com)?
At the moment:
Should be:
My Code:
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /(https?:\/\/[^\s]+)/g;
$("#textarea").val().replace(urlRegex, function(url) {
var link = '<div>' + url + '</div>';
// Append the new information to the existing information
result.append(link);
});
});
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea"></textarea>
<div id="converted_url"></div>
JS FIDDLE
Credits
Scott Marcus, Stackoverflow
Simple fix: store matched urls in array and append link only if url is not present in that array.
UPDATE: changed regex to /((https?:\/\/|www\.|\/\/)[^\s]+)/g so it matches links starting with http://, https://, www., //. You may use any other regex covering other cases (like http://www.) just modify stored url so that you'll be able to compare it (you may want to treat http and https link as unique).
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /((https?:\/\/|www\.|\/\/)[^\s]+)/g;
var found = [];
$("#textarea").val().replace(urlRegex, function(url) {
let trimmedUrl = url.replace(/^(https?:\/\/|www\.|\/\/)/, "");
if (found.includes(trimmedUrl)) {
return;
}
found.push(trimmedUrl);
var link = '<div>' + url + '</div>';
// Append the new information to the existing information
result.append(link);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(Just type anything in the box to trigger the event.)<br>
<textarea id="textarea">http://google.com blah blah http://facebook.com</textarea>
<div id="converted_url"></div>
let result = $("#converted_url");
$("#textarea").on("input", function() {
result.html(""); // Reset the output
var urlRegex = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9]\.[^\s]{2,})/g;
var found = [];
$("#textarea").val().replace(urlRegex, function(url) {
var link = "";
var protOmmitedURL = url.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
if (found.includes(protOmmitedURL)) {
return;
}else
{
link = '<div>' + url + '</div>';
found.push(protOmmitedURL);
}
// Append the new information to the existing information
result.append(link);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(Just type anything in the box to trigger the event.)<br>
<textarea id="textarea">http://google.com blah blah http://facebook.com</textarea>
<div id="converted_url"></div>

how to use url parameters in html? [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 4 years ago.
I get URL parameters using Javascript but i can't use those variables in my html.
the JS code is this:
<script>
var url_string = window.location.href; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("name");
console.log(c);
</script>
and my URL is localhost:8000/something?name=ABC.here i can get the value of name and show it in the browser console but when i try to set the value of an input tag in my HTML it doesn't do it and raises some errors.
my JS and html is like:
<script>
var url_string = window.location.href; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("name");
document.getElementById("user").value =url.searchParams.get("name");
</script>
<input id="user" value"">
this should have changed the value of the input tag but doesn't.
if your #user input is call before the DOM content is loaded,
document.getElementById("user").value
javascript can't find it so he try to set "value" of an undefined element
try this :
<input id="user" value="">
<script>
var url_string = window.location.href; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("name");
document.getElementById("user").value = c;
</script>
If you only have one URL parameter this will work. Just make sure that your input element is defined first.
A working copy JsFiddle static input
HTML
<input id="user" value="">
JS
var url = "localhost:8000/something?name=ABC" //replace with code to get url
var name = url.substring(url.indexOf("=") + 1);
document.getElementById("user").value = name;
If you need the input element to be defined after you get the URL parameter:
A working copy JsFiddle dynamic input
HTML
<div id="myDiv"> </div>
JS
var url = "localhost:8000/something?name=ABC" //replace with code to get url
var name = url.substring(url.indexOf("=") + 1);
var parent = document.getElementById("myDiv");
var input = document.createElement("input");
input.value = name;
parent.appendChild(input)

Excluding a specific link with Autolinker.js

I am using Autolinker.js to linkify text inputted from a form, but I would like to exclude example.com from being linked.
var formInput = "Don't link example.com but link google.com and www.kbb.com please";
var linkedText = Autolinker.link(formInput);
naturally yields linkedText having both urls linkified. I tried changing the url options using
var options = {urls: { schemeMatches: true, wwwMatches: true, tldMatches: false }};
var linkedText = Autolinker.link(formInput, options);
but this eliminates the link on google.com as well as the example.com while leaving www.kbb.com linked.
Basically I just want to exclude a single specific url, namely example.com, from being linked.
Sorry that I just noticed this thread. I'm the library author. I know it's pretty late but leaving this reply for anyone else who comes across it.
The easiest way to exclude a particular url from being autolinked is to leverage the replaceFn option. For example:
var formInput = "Don't link example.com but link google.com and www.kbb.com please";
var linkedText = Autolinker.link( formInput, {
replaceFn: function( match ) {
if( match.getType() === 'url' ) {
var url = match.getUrl();
if( url.indexOf( 'example.com' ) !== -1 ) {
return false; // don't autolink matches for example.com
}
}
return true; // autolink everything else as usual
}
} );
This produces the result of:
Don't link example.com but link google.com and kbb.com please
Here is some documentation on the methods that can be called on UrlMatch objects: http://greg-jacobs.com/Autolinker.js/api/#!/api/Autolinker.match.Url
And a more in-depth example of using replaceFn: https://github.com/gregjacobs/Autolinker.js#custom-replacement-function
Replace text with a token, run autolink, replace token with original text. The obvious weakness here is that if formInput contained ||anything|| it would break.
var formInput = "Don't link example.com but link google.com and www.kbb.com please";
var stuffIdontwanttolink = ['example.com', 'google.com'];
stuffIdontwanttolink.forEach(function(entry, index) {
formInput = formInput.replace(entry, '||' + index + '||');
});
console.log(formInput);
//var linkedText = Autolinker.link(formInput);
var linkedText = "Don't link ||0|| but link ||1|| and <a href='//www.kbb.com'>www.kbb.com</a> please"; // Simulated
stuffIdontwanttolink.forEach(function(entry, index) {
linkedText = linkedText.replace('||' + index + '||', entry);
});
console.log(linkedText);
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
So I wrote a function to wrap the Autolinker in:
function excludedLinkify (inputText) {
var exclusions = [
{url:'example.com', temp:'7g578v43gc7n3744c'}
];
$.each(exclusions, function (i, e) {
inputText = inputText.replace(e.url, e.temp);
});
inputText = Autolinker.link(inputText);
$.each(exclusions, function (i, e) {
inputText = inputText.replace(e.temp, e.url);
});
return inputText;
}
So that to achieve the desired result I can now
var formInput = "Don't link example.com but link google.com and www.kbb.com please";
var linkedText = excludedLinkify(formInput);

is there a way to use javascript or jquery to add a color to the search keyword

the url is like this:
http://www.example.com/index.php?main_page=advanced_search_result&keyword=Sons+of+Anarchy
on the above the search keyword is Sons of Anarchy. now, is there a way to add a color to the keyword when in the search result content with js on the search result page . thank you.
ps:the search input box:<input type="text" class="keybg" id="keyword" name="keyword">
$sData['pfrom'] = (isset($_GET['pfrom']) ? zen_output_string($_GET['pfrom']) : '');
$sData['pto'] = (isset($_GET['pto']) ? zen_output_string($_GET['pto']) : '');
the above way is added a parameter to the url.
http://www.example.com/index.php?main_page=advanced_search_result&keyword=Sons+of+Anarchy&pfrom=...pto=..
You could do something like this:
document.body.innerHTML = document.body.innerHTML.replace(/Anarchy/ig, '<mark>Anarchy</mark>');
Try this (this assumes you are loading jQuery into the page):
myFile.php
==========
<?php
$sData['pfrom'] = (isset($_GET['pfrom'])
? zen_output_string($_GET['pfrom'])
: '');
$sData['pto'] = (isset($_GET['pto'])
? zen_output_string($_GET['pto'])
: '');
// ... your other code here
?>
<!-- PUT THIS SCRIPT AT THE END OF YOUR HTML BODY ELEMENT -->
<script type="text/javascript">
// get the current URL
var url = window.location.toString();
//get the parameters
url.match(/\?(.+)$/);
var params = RegExp.$1;
// split up the query string and store in an
// associative array
var params = params.split("&");
var queryStringList = {};
for (var i=0;i<params.length;i++) {
var tmp = params[i].split("=");
queryStringList[tmp[0]] = unescape(tmp[1]);
}
// get the body html and update it to have keyword colored
var searchKeyword = queryStringList.keyword;
var searchRegex = new Regexp('/'+searchKeyword+'/', 'gi');
var html = $('body').html();
var coloredHTML = html
.replace(searchRegex,
"<span style="color:green">"+html+"</span>");
$('body').html(coloredHTML);
</script>
I think what you want is something like this.
The solution will not mess up your html if you are searching for something that is probably inside html tags, e.g., span
The search key will be escaped in order to generate a correct reg exp object
code:
var searchKey = 'rray($';
highlight(searchKey, $('div'));
searchKey = '|| !';
highlight(searchKey, $('div'));
function highlight(word, $target){
var conts = $target.html().split('<').join('><').split('>');
var escapeRgx = /([\/\.\*\+\?\|\(\)\[\]\{\}\\\:\$\^])/g;
var searchRgx = new RegExp(word.replace(escapeRgx, '\\$1'), 'gi');
$.each(conts, function(idx, str){
if(str.charAt(0) != '<'){
conts[idx] = str.replace(searchRgx, '<span class="mark">' + word + '</span>') ;
} else {
conts[idx] = str + '>';
}
});
$target.html(conts.join(''));
}
For getting the search key, you can retrieve it at the backend, and echo it to the frontend. i.e.,
<? echo 'var searchKey = "'. $_GET['key'] .'"'; ?>
Here is the demo -
http://jsfiddle.net/jn7TC/4/

Categories

Resources