How do I render a variable in a URL path in JavaScript? - javascript

I have the following line:
var myCustomVariable = '3434';
urlpath = '/people/myCustomVariable/folders/byid/'
I want to render the value of myCustomVariable in the urlpath but being new to JS I am unable to figure this out. I tried doing the following but didn't work:
"+myCustomVariable+"!"
What am I doing wrong?

You use the + operator:
var myCustomVariable = '3434';
urlpath = '/people/' + myCustomVariable + '/folders/byid/'
This is called "concatenation" or (because we're dealing with strings) "string concatenation."
Your "I tried doing the following..." uses double quotes and a !. I'm not sure where the ! comes from, but in JavaScript, if you open a string with a single quote, you must end it with a single quote; and if you open it with a double quote, you must end it with a double quote.

Just do the concatenation of strings like this:
var myCustomVariable = '3434';
urlpath = '/people/' + myCustomVariable + '/folders/byid/'
When you do this:
"+myCustomVariable+"
That represents a string, not your variable. Your variable is
myCustomVariable
Without the " aroud it
See this:
var myCustomVariable = '3434';
//This
urlpath = '/people/' + myCustomVariable + '/folders/byid/'
//Same than
urlpath = '/people/' + '3434' + '/folders/byid/'
//Same than
urlpath = '/people/3434/folders/byid/'
But
var myCustomVariable = '3434';
//This
urlpath = '/people/' + '+myCustomVariable+' + '/folders/byid/'
//Same than
urlpath = '/people/+myCustomVariable+/folders/byid/'

Related

How to change the pathname of url in jquery/javascript

I want to change the pathname of the url, i tried but the complete url is getting modified. I need the last value of the url only needs to change.
this is what I am expecting:
Current URL : localhost:8080/abc/index.html
Expecting URL : localhost:8080/abc/test.html
THis is what I tried:
window.location.pathname = window.location.pathname.substring(window.location.pathname.lastIndexOf('/')+1);
It is returning only localhost:8080/test.html
Try something like this:
var parts = window.location.href.split("/");
if (parts[parts.length - 1].length < 1) {
parts = parts.splice(parts.length - 1, 1);
}
parts[parts.length - 1] = 'test.html';
parts = parts.join("/");
console.log(parts);
It looks like you almost have what you want, check this:
var pathname = "localhost:8080/abc/index.html";
var lastItem = pathname.substring(pathname.lastIndexOf('/')+1);
alert('Last item: ' + lastItem);
var startPart = pathname.substring(0, pathname.lastIndexOf('/')+1);
alert('Start part: ' + startPart);
var newUrl = startPart + 'test.html';
alert('New url: ' + newUrl);

Replace the backslash with space in JavaScript

k = "hello'S";
var sym = k.replace(/\'/g,"\\'");
I want my output to look like: hello's
I am getting it now as hello\'s
From your comment (with various typos fixed):
var k = "hello's";
var sym =k.replace(/\'/g,'\\\'');
onclick = "gosymbol(\''+k+'\',event);
by doing this i am getting output as hello\'s but i wanted it to be like hello's
So what you're trying to do is embed a string in an onclick handler as text. That's not a good idea, not least because of the quoting hassles. Instead:
someElement.onclick = gosymbol.bind(someElement, k);
Live Example:
var k = "hello's";
var someElement = document.getElementById("some-element");
someElement.onclick = gosymbol.bind(someElement, k);
function gosymbol(arg, e) {
alert("gosymbol got: [" + arg + "], event type: " + e.type);
}
<div id="some-element">Click me</div>
If for some reason it has to be a string, then the problem is that you didn't have the right number of ' characters in your onclick line, and had k in the string literally (which means you weren't getting the output you described), and weren't using sym:
var k = "hello's";
var sym = k.replace(/'/g, "\\'");
onclick = "gosymbol('" + sym + "',event);";
I do not suggest doing that, but if that's what you want to do...
Live Example:
var someElement = document.getElementById("some-element");
var k = "hello's";
var sym = k.replace(/'/g, "\\'");
someElement.setAttribute("onclick", "gosymbol('" + sym + "',event);");
function gosymbol(arg, e) {
alert("gosymbol got: [" + arg + "], event type: " + e.type);
}
<div id="some-element">Click me</div>

javascript replace all is not working?

I have to replace all the special character form the html and i have created an array of special character having key value pairs of special characters and class name .
But this is not working . I have tried and the following is the code and fiddle link.
var SpClass = new Array();
SpClass["&"] = "ampClass";
function temp() {
var str = "";
var tempLen = SpClass.length;
var k = 0;
var htmlForRemoveChar = $("#test").html();
for (var splChar in SpClass) {
if (k > tempLen) {
$("#test").html(htmlForRemoveChar);
}
var tempChar = "/" + splChar + "/g";
alert(htmlForRemoveChar);
htmlForRemoveChar = htmlForRemoveChar.replace(tempChar, '<span class="specialChar "' + SpClass[splChar] + '"">W</span>');
alert(htmlForRemoveChar);
k++;
}
$("#test").html(htmlForRemoveChar);
}
<div id="test">this is test & i am doing testing</div>
<input type="button" onclick="temp();" value="Remove&">
http://jsfiddle.net/aps123/y4McS/1/
You just need to change this line:
var tempChar = "/" + splChar + "/g";
To:
var tempChar = new RegExp(splChar, 'g');
At present you're replacing a literal String, e.g. '/a/g'. If you need to dynamically create the contents of a regex then you need to use RegExp. If the contents is static then you can use a regex literal.
Try replacing replace(tempChar with replace(new RegExp(splChar, 'g').
It looks like you are using a string literal, not a regex literal. A regex literal is like this:
var x = /x/g;

Add .html to a string Javascript?

I want to check if a string is ending with ".php" extension, if not I want to add .html at the end. I have already tried various "slice" methods without success.
You can use Regex for that
var string1 = "www.example.com/index";
var newString = !/\.php$/i.test(string1)? string1+".html": string1;
// newString = "www.example.com/index.html"
Use (yourstring + '.html').replace(/\.php\.html$/, '.php') to do that:
var str1 = 'one.php';
var str2 = 'two';
var str3 = '.php.three.php';
var str4 = '.php.hey';
console.log((str1 + '.html').replace(/\.php\.html$/, '.php')); // Prints one.php
console.log((str2 + '.html').replace(/\.php\.html$/, '.php')); // Prints two.html
console.log((str3 + '.html').replace(/\.php\.html$/, '.php')); // Prints .php.three.php
console.log((str4 + '.html').replace(/\.php\.html$/, '.php')); // Prints .php.hey.html
Or perhaps:
function appendHTML(string) {
var html = string;
if (string.lastIndexOf('.php') === (string.length - 4)) {
html += '.html';
}
return html;
}
Well, slice() works ok for this task.
var s = "myfile.php";
if (s.slice(-4) != ".php")
s = s.slice(0, -4) + ".html";
Use regular expression to solve your problem.
/.php$/ is a regular expression that checks to see if a string ends with '.php'
For more information read: http://www.w3schools.com/js/js_obj_regexp.asp
Example Code:
str = "http://abc.com";
str = ( /\.php$/.test( str ) ) ? str : str + '.html'; // this is the line you want.
str === "http://abc.com.html" // returns true
Try something like this
function isPHP(str)
{
return str.substring(str.length - 4) == ".php";
}
Then you could do
str = isPHP(str) ? str : str + ".html";

How to pass 2 JavaScript variables through a url?

I am trying to have 2 variable values passed in a url, which url will be redirected after. How can I insert them in a JavaScript string?
I have:
var a = document.getElementById("username_a").value;
var b = document.getElementById("username_b").value;
and want something like: var string_url = "http://www.example.com/?{a}blabla={b}" and then redirect somehow.
In PHP I would go with that code for example: <iframe src="http://www.example.com?query=<?php echo $the_variable;?>">
You can add strings in JavaScript, "a" + "b" == "ab" evaluates to true.
So what you want is probably var string_url = "http://www.example.com/?" + a + "&blabla=" + b;
But you should ever escape vars especially if they come from inputs, so try
a = encodeURIComponent(a);
b = encodeURIComponent(b);
And then
var string_url = "http://www.example.com/?" + a + "&blabla=" + b;
To redirect you can use window.location:
window.location = string_url;
use the ampersand to split vars
var string_url = "http://www.example.com/?" + "username_a=" + a + "&username_b=" + `b
Could be made more sopisticated, but that in essence is what you need
JavaScript doesn't do string interpolation. You have to concatenate the values.
var uri = "http://example.com/?" + encodeUriComponent(name_of_first_variable) + "=" + encodeUriComponent(value_of_first_variable) + '&' + encodeUriComponent(name_of_second_variable) + "=" + encodeUriComponent(value_of_second_variable);
location.href = uri;

Categories

Resources