How to convert value assigned to variable as String - javascript

I have limited knowledge of javascript,so hoping someone can help.
Tried w3 schools & stacko using Document.
This is a dumb question.
We receive a variable value that outputs string without quotes.The string has spaces.
In the example below is it possible to add quotes to my string.
how do i use a input value without quotes and parse it as string?
myvar = John doe
is it possible to add Quotes to a value assigned to a variable?
<html>
<body>
<div id="param">my string</div>
<div id="base64param"></div>
<div id="encodeparam"></div>
<div id="myframe"</div>
<div id="myframe2"</div>
<iframe id="myframe" src="" width="400" height="800" frameborder="0">
</iframe>
<script>
window.onload = function myFunction() {
var str = document.getElementById("param").innerHTML;
var base64param = window.btoa(str);
document.getElementById("base64param").innerHTML = "base64:" + base64param;
var encodeparam = encodeURIComponent(str);
document.getElementById("encodeparam").innerHTML = "encoded:" + encodeparam;
var appurl = "http://localhost/index.jsp?param=";
var furl = appurl + str;
document.getElementById("myframe").innerHTML = "URLwithout encode:" + furl;
var burl = appurl + base64param;
document.getElementById("myframe2").innerHTML = "URLwith encode:" + burl;
}
</script>
</body>
</html>

If you have an existing variable, and want to add quotes:
var varWithQuotes = "\"" + oldVar + "\"";
The slash is an escape character and the plus sign is how to concatenate strings.

Related

How can I pull a segment of the current page URL (last five digits) into an iFrame within the page, in Wordpress?

Our website uses Wordpress, and we pull our job openings from the software using an iFrame. The iFrame query requires us to get the job "code" from the URL (e.g. xyz.com/job-details/jobcode=11568).
The vendor has provided javascript that is supposed to do this, but it does not work. When the page loads the src just outputs as src(unknown)". The iframe should read as src="https://evoportalus.tracker-rms.com/COMPANY/jobs?fields=title,location&filters=Reference|<<the jobcode pulled from the URL>>
Can anyone help?
<script type="text/javascript">
loadSite();
</script>
<iframe src="" frameborder="0" scrolling="yes" width="700" height="700" id="trmsjobs"></iframe>
<script type="text/javascript">
var getQueryString = function (field, url) {
var href = url ? url : window.location.href;
var reg = new RegExp('[?&]' + field + '=([^&#]*)', 'i');
var string = reg.exec(href);
return string ? string[1] : null;
};
function loadSite() {
var site = "https://evoportalus.tracker-rms.com/LincolnStrategic/jobs";
site += "?fields=title,location&filters=reference|" + getQueryString("jobcode");
document.getElementById('trmsjobs').src = site;
}
</script>
On Edit
Apologies, I don't think my original explanation was clear enough. The getQueryString variable seems to work; it outputs just fine. The issue is that the "site" variable is not being inserted into the SRC value in the iFrame, which is what this script is supposed to do.
Tweak your code to move the function call into the same block and change var functionName = function syntax to function functionName syntax
<iframe src="" frameborder="0" scrolling="yes" width="700" height="700" id="trmsjobs"></iframe>
<script type="text/javascript">
loadSite();
function getQueryString (field, url) {
var href = url ? url : window.location.href;
var reg = new RegExp('[?&]' + field + '=([^&#]*)', 'i');
var string = reg.exec(href);
return string ? string[1] : null;
};
function loadSite() {
var site = "https://evoportalus.tracker-rms.com/LincolnStrategic/jobs";
site += "?fields=title,location&filters=reference|" + getQueryString("jobcode");
console.log(site);
document.getElementById('trmsjobs').src = site;
}
</script>
You can split the string with "/", then look for each component for the parameter you want, splitting this time with "=". Not a clean solution, but works:
var getQueryString = function(field, url){
var ret=null;
url.split("/").forEach(function(v){
var s=v.split("=");
if(s.length>1 && s[0]==field){
ret=s[1];
return;
}
});
return ret;
}

String replace logic

I'm trying to build a function, that receives a string with this format:
"hello wor**"
The * could be anywhere on the string.
It should return:
<span>hello wor</span><input type='text'></input>
So the string could be "hel** wor*d" also
and the return should be:
<span>hel</span><input type='text'> <span>wor</span><input type='text'><span>d</span>
I could do it easily with a loop on each char, but I'm looking for more elegant solutions.
I think that it could be solved with a regex, and using replace I got the "*" covered:
var text = "hello wor**";
text.replace(/\*+/g, "<input type='text'></input>");
I have not yet found a way of capturing the remaining text to render the
<span>
You're not using the result of the replace function. Try this:
var text = "*hel** wor*d*";
var element = text.split(/\s*\*+\s*/g);
element = "<span>"+ element.join("</span><input type='text'><span>") + "</span>";
element = element.replace(/<span><\/span>/g, "");
console.log(element);
'hello wor**'.replace(/\*+/g, "<input type='text'></input>");
This returns hello wor. All you have to do is concatenate the string with the rest of the data you want, like so:
var text = "hello wor**";
text = '<span>' + text.replace(/\*+/g, '') + '</span><input type=\'text\'></input>';
<html>
<head>
</head>
<body>
<span id="hi">hello wor**</span>
</body>
</html>
i use jquery in this
$( document ).ready(function() {
var texty = $('#hi').text();
$('#hi').replaceWith(texty.replace(/\*+/g, "<input type='text'></input>"))
});

How to show two random strings from separate arrays in one <p> tag

I'm new to JS and I am trying to make two random strings that were selected by using math.random() and put them into my p tag so that I could end up with something like 'Storm Breaker' or 'Castle Eater', but it seems I can only display the first name (fname) or the last name (lname). I tried to do
document.getElementById("print").innerHTML=fname,lname;
That didn't work so I also tried:
document.getElementById("print").innerHTML=fname;
document.getElementById("print").innerHTML=lname;
But as you could tell that would just change where the first name would be into the last name.
<h1 class="title">Welcome to Tom's Random Name Generator!</h1>
<button type="button" onclick="myFunction();">Generate!</button>
<p id="print"></p>
<script>
function myFunction() {
var fnamel = ['Storm','Wind','Castle','Chocolate','Savage'];
var lnamel = ['Breaker','Eater','Smasher','Killer','Fury'];
var fname = fnamel[Math.floor(Math.random()*fnamel.length)];
var lname = lnamel[Math.floor(Math.random()*lnamel.length)];
document.getElementById("print").innerHTML=fname;
}
</script>
Change like this :
document.getElementById("print").innerHTML=fname + " " + lname;
Final code :
<html>
<head>
<style>
</style>
</head>
<body>
<h1 class="title">Welcome to Tom's Random Name Generator!</h1>
<button type="button" onclick="myFunction();">Generate!</button>
<p id="print"></p>
<script>
function myFunction() {
var fnamel = ['Storm','Wind','Castle','Chocolate','Savage'];
var lnamel = ['Breaker','Eater','Smasher','Killer','Fury'];
var fname = fnamel[Math.floor(Math.random()*fnamel.length)];
var lname = lnamel[Math.floor(Math.random()*lnamel.length)];
document.getElementById("print").innerHTML=fname + " " + lname;
}
</script>
</body>
</html>
You can concatenate strings in javascript using the plus operator.
document.getElementById("print").innerHTML=fname + ' ' + lname;

How to get text of div by id in variable

I have a string variable called the res.
Within this variable there is HTML code.
Each Div in variable within the has a id.
var res = "<div id="1">1</div>
<div id="2">12</div>
<div id="3">123</div>
<div id="4">1234</div>";
var content-div-1 = ??;
var content-div-2 = ??;
var content-div-3 = ??;
var content-div-4 = ??;
I would like to give the id of div and give me values of inside Div.
The question has been answered, but there's an alternative without jQuery
var res = '<div id="1">1</div>'+
'<div id="2">12</div>'+
'<div id="3">123</div>'+
'<div id="4">1234</div>';
function findMe(txt, id){
var matches = txt.match(new RegExp('<div\\s+id="'+id+'">[\\S\\s]*?<\\/div>'), 'gi');
if(matches) return matches[0].replace(/(<\/?[^>]+>)/gi, '');
return '';
}
var content1 = findMe(res,1);
var content2 = findMe(res,2);
var content3 = findMe(res,3);
var content4 = findMe(res,4);
JSFiddle
As you've tagged your question jquery, I assume this is in a browser context (or some other context with a DOM). If so, the simplest way to is to parse the HTML and use the resulting disconnected DOM tree:
var res = '<div id="1">1</div>' +
'<div id="2">12</div>' +
'<div id="3">123</div>' +
'<div id="4">1234</div>';
var parsed = $(res);
var contentDiv1 = parsed.filter("[id=1]").text(); // See note below
snippet.log("1: " + contentDiv1);
var contentDiv2 = parsed.filter("[id=2]").text(); // See note below
snippet.log("2: " + contentDiv2);
// ...and so on (or use a loop)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Note: Although id value starting with digits are valid HTML, it's awkward to use them because in a CSS id selector (#foo), you can't start the ID value with an unescaped digit (e.g., #1 is an invalid selector). That's why I've had to use the attribute selector [id=1] above. You can work around it with escaping, but by far the best option is just to not start ID values with digits in the first place.

How to show a string on a page

This is a really stupid question.
I have a javascript string variable for a name, and i want to display it where it says user like this:
"Hello, user!" --> "Hello, Chris!
Surely you could have found this answer out easily yourself :p
Put the name in a span and give it an ID
Hello <span id="name"></span>
Then set the text using getElementByID
var name = "Chris";
document.getElementById('name').innerHTML = name;
var user_name = 'Chris';
document.writeln("Hello, " + user_name);
I think document.write plus some string concatenation are what you're looking for:
var user = "Chris";
document.write("Hello, " + user + "!");
Something like this will do the trick.
var user = 'Steve';
document.write('hello ' + user);
If you need to target an element, you can use the usual methods, such as:
var user = 'Steve';
var thisOne = document.getElementById('thisOne');
thisOne.innerHTML = ('hello ' + user);
May as well throw in a jsfiddle so you can play around an experiment.
This is example of dislay string into span tag.
'+' operator uses for string concatenation.
<html>
<head>
<script>
var name = 'Chris';
var field = document.getElementById('show_string');
field.innerHTML( '"Hello, '+ name + '!"' );
</script>
</head>
<body>
<span id='show_string'></span>
</body>
</html>
You can concatenate the user's name with the rest of the string you want to display like so:
<p id="hello"></p>
<script type='text/javascript'>
var user_name = "Chris";
var hello_string = "Hello, " + user_name;
document.getElementById("hello").innerHTML = hello_string;
</script>

Categories