Fixing the URl so there is no spaces - javascript

I have a button that has its location generated dynamically via jquery:
<a id="final_location"
href="/pre_config/step4"
class="proceed-btn right">Proceed To Next Step >>></a>
$('#final_location').click(function() {
location.href = this.href + '/' + escape($('#type_of_station').html()) +
'/' + escape($('.number_changer').attr("id").slice(-1));
return false;
});
this works great but the problem comes into play when the html in type_of_station is two words... I get this url:
pre_config/step4/Pizza Delivery/2
Is there a way to make the url only give me the first word like this:
pre_config/step4/Pizza/2
maybe this can be changed to only return the first word?

Use
encodeURIComponent($('#type_of_station').text().match(/^\S*/)[0])
instead of escape($('#type_of_station').html()) to get the first word (separated by space).

This should get you the first word in the phrase:
var type = $('#type_of_station').html();
var i = type.indexOf(' ');
if (i != -1) type = type.substr(0, i);

You could do:
var name = "Pizza Delivery";
var pieces = name.split(" ");
alert(pieces[0]); // Pizza
Or just do:
var name = "Pizza Delivery";
name = name.replace(/\s/g, "-", name); // feel free to change the - delimiter
alert(name); // Pizza-Delivery

Related

add to URL after last /

using jQuery; to add something to a url after the last /
for example add sale to:
/gender/category/brand/
so it becomes:
/gender/category/brand/sale
However due to the way the URL's are generated and built I can't just always say 'add it to the end of a URL' as there are sometimes ?query strings on the end for example:
/gender/category/brand/?collection=short&colour=red
I just can't figure out how I can add sale after the final / and always before a ?query string if one exists.
Searching through stackoverflow I've seen some bits about extracting content after the last / but not this, is this possible? I really would appreciate help getting this sorted.
EDIT - The solution
Thanks too all for your help but I was able to adapt Shree's answer the easiest to get this which did what I needed:
if(window.location.href.indexOf("sale") > -1) {
} else {
var raw = window.location.href;
var add = 'sale';
var rest = raw.substring(0, raw.lastIndexOf("/") + 1);
var last = raw.substring(raw.lastIndexOf("/") + 1, raw.length);
var newUrl = rest + add + last;
window.location.href = newUrl;
}
Use substring with lastIndexOf.
var raw = '/gender/category/brand/?collection=short&colour=red';
var add = 'sale';
var rest = raw.substring(0, raw.lastIndexOf("/") + 1);
var last = raw.substring(raw.lastIndexOf("/") + 1, raw.length);
var newUrl = rest + add + last;
console.log(newUrl);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In vanilla javascript
var a = "/gender/category/brand/?collection=short&colour=red";
var lastIndexPosition = a.lastIndexOf('/');
a = a.substring(0,lastIndexPosition+1)
+"sale"
+a.substring(lastIndexPosition+1 , a.length);
console.log(a);
By using a reusable function in Javascript:
You can use lastIndexOf and get the last '/' index position and append your new data there.
The lastIndexOf() method returns the position of the last occurrence
of a specified value in a string.
Using this you can send any parameter into function there by it is reusable.
function insert(main_string, ins_string, pos) {
return main_string.slice(0, pos) + ins_string + main_string.slice(pos);
}
var url = "/gender/category/brand/?collection=short&colour=red"
url = insert(url, 'sale', url.lastIndexOf("/") + 1)
console.log(url)
Here is a working DEMO
An alternative, use .split("?") to separate at the ? then combine them back, eg:
// Example with querystring
var url = '/gender/category/brand/?collection=short&colour=red'
var parts = url.split("?");
var newurl = parts[0] + "sale" + "?" + (parts[1]||"")
console.log(newurl)
// Test without querystring
var url = '/gender/category/brand/'
var parts = url.split("?");
var newurl = parts[0] + "sale" + (parts[1]||"")
console.log(newurl)
The (parts[1]||"") handles the case where there isn't a querystring.

Removing Url and Include Id using Regex and Jquery

I am new to Regex and my question is how can i include the ID from the url and remove it using Regex? because as of now , It only removes the actionMe=reload&Id= but the Id still return so after removing it and replacing with new Url, the old id is still included plus the new ID,
Example, Before removing and replacing the Url:
http://localhost:2216/Main/WorkerPage?workerId=10&actionMe=reload&Id=15
And After Removing and replacing the url , it goes like this:
http://localhost:2216/Main/WorkerPage?workerId=10&actionMe=reload&Id=1615
This is my Code Snippet:
var sss = $("#Id").val();
if (window.location.href.indexOf("&actionMe=reload&Id=") > -1) {
var regex = /(\&|&)actionMe=reload&Id=/;
var location = window.location.href;
if (regex.test(location)) {
window.location = location.replace(regex, "&actionMe=reload&Id=" + sss)
}
}
Thanks for Answering guys:)
you can use this code to update url parameters
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
}
I got it here
Now, in your case, you can use it like this
var url = window.location.href;
var sss = $("#Id").val();
var newUrl = updateQueryStringParameter(url, "id", sss);
//do whatever you want to newUrl
//to redirect to new url
window.location = newUrl;
Pretty sure all you need is /&Id=\d+/ as your RegExp. Don't need to select any of actionMe=reload unless you need that for specification (in that case, just add it back). The rest of your code works as intended, just your regex not selecting the precise part you were wanting.
Explanation:
The (\&|&) part of your regex is redundant, as & does not need to be escaped to work. As a matter of fact, since it's in parenthesis, you would end up capturing that & character, if you REALLY need that part, try (?:\&|&) to ignore the capture group. Your code replaced the matched regex, but did not include the number "15" after Id=, which is why it appended 15 after your edited version due to it not being matched and therefore not being replaced. Adding \d+ will select any trailing digits. This should give you the result you wanted.

Javascript : Detect if a String contain url image

I have the following String :
var str = "Hello, i would like to show this image : http://logonoid.com/images/stack-overflow-logo.png" ;
I would like to create a function which detect the presence of image urls and return a 2 things :
The new String without the image url
An array containing image url found in the String.
How can i do that ?
You can try something like this, i am checking for an image file extension
var str = "Hello, i would like to show this image : http://logonoid.com/images/stack-overflow-logo.gif" ;
var test = (/\.(gif|jpg|jpeg|tiff|png)$/i).test(str)
if it finds a match it will return true otherwise false
Fiddle
You can use the following to match:
(https?:[^\s]+)
Group 1 will give the list of urls.. you can replace them with '' empty string to get the new string.
See DEMO
Are you familiar with regular expressions? Because the things you ask are pretty easy:
the regex to detect an URL is
^(http|https)://
and in Javascript that would be:
str.match(^(http|https)://);
Now it is up to you to find out how to save the correct output.
Simple way could looks like that
var str = "Hello, i would like to show this image : http://logonoid.com/images/stack-overflow-logo.png" ;
console.log(str.includes(":"));
if(str.includes(":") && ( (str.includes("http") || str.includes("https")) )){
var newOutput = str.split(":");
for(var i in newOutput){
console.log("[" + i + "]: " + newOutput[i]);
}
var message= newOutput[0];
var urlImage= newOutput[1] + newOutput[2];
console.log("message: " + message +" , URL: " + urlImage);
}else{
console.log("no URL find");
}
You can use match for that "if" and it will looks better :o)
Shortest way to do it I think:
console.log(newVal.match(/\.(jpeg|jpg|png|gif)/g) != null);
if it finds a match it will return true otherwise false

passing a variable to map & replace

I am trying to "clean" a text string that looks something like this:
DATABASE:madsat NL:Show all platforms of Salute generated from NAIs with no go mobility.
The cleaned string should look like this:
Show all platforms of Salute generated from NAIs with no go mobility.
I am trying the following code but it doesn't seem to like it when I pass in a variable as the string gets returned unchanged:
$(document).ready(function(){
$.get('inputQueryExamples.txt',function(data){
var queryString = data;
var cleanString = "";
var db = '';
$('#database-list').change(function(){
db = $('#database-list').val();
// /(^DATABASE:.*\r\n)(^NL.*)/gm
// http://regex101.com/r/mN4hS2
regex = new RegExp('(^DATABASE:'+ db +'\r\n)(^NL.*)' ,'gm');
console.log(db);
console.log(regex);
//put code in here to replace un-needed stuff
$('#what').append(regex + '<br>');
cleanString = queryString.match(regex);
var nlString = cleanString.map(function(el) {return el.replace('DATABASE:' + db + ' NL:','');});
for (i=0; i<nlString.length; i++){
$('#what').append(nlString[i]+'<br>');
}
}); // end change
Any insight into what i am doing wrong will be appreciated. Thanks
So this works, but I am not sure why I have to process the string twice. Can anyone explain?
var nlString = cleanString.map(function(el) {return el.replace('DATABASE:' + db,'');});
nlString = nlString.map(function(el){return el.replace('NL:',''); });
Something like this?
var s = "DATABASE:madsat \r\nNL:Show all platforms of Salute generated from NAIs with no go mobility.";
var db = "madsat";
var r = new RegExp('(^DATABASE:'+ db + '[\\s\\r\\n]*)(^NL:)' ,'gm');
s1.replace(r, "");
//=> "Show all platforms of Salute generated from NAIs with no go mobility."
Update
It took a while for what you're trying to do to sink in (and your sample data was pretty buried in that regex101 link.)
But I think this JSBin is something close to what you want to do: It still does one pass to find the matches, and a second one to remove the unwanted parts of that match. But the second pass is handled by a single regex replace call rather than your double replaces above. (Click the "Run with JS" button and enter "madsat" or "geoquery" in the box.)
This is the relevant code:
$(document).ready(function() {
$.ajax('http://jsbin.com/fase/1.js', {dataType:'text'}).done(function(data){
var $what = $("#what");
$('#database-list').change(function(){
var db = $(this).val(),
base = '(^DATABASE:'+ db + '[\\s\\r\\n]*)(^NL:)';
var regex1 = new RegExp(base + '(.*)' ,'gm');
var regex2 = new RegExp(base, 'gm');
(data.match(regex1) || []).map(function(str) {
return str.replace(regex2, "");
}).forEach(function(query) {
$what.append(query + "<br/>");
});
});
});
});
Note that the two regexes are identical except that the first one matches the remainder of the "NL:"-line, and the second one doesn't.

Probably a easy thing to do but how do I get javascript to only split if something is there, if not leave it as is

I'm using the following to get the title from a feed:
var posttitleGETcalendar = entry.title.$t;
var posttitleREMcalendar = posttitleGETcalendar.split("_");
var title = posttitleREMcalendar[0] + "<small>" + posttitleREMcalendar[1] + "</small>";
What I'm trying to do is split the titles I get after underscore and add the tag small to the part after it.
Works great when underscore is there, but it shows the word undefined after last word if underscore is not on title.
Is there a way to use
if underscore is on title, do
if not, leave it as is
Thank you.
if(/_/.test(posttitleGETcalendar)) {
// posttitleGETcalendar.indexOf('_') != -1 would do too
// do your stuff here
}
alternatively, you could use the replace method and skip the other auxilliar variables :
var title = entry.title.$t.replace('_', '<small>') + '</small>';
You can change the last line to:
var title = posttitleREMcalendar[0]
if ( posttitleREMcalendar.length > 1 )
{
title = title + "<small>" + posttitleREMcalendar[1] + "</small>";
}
This way you will only add the second part if it's present.

Categories

Resources