I'm trying to alert the last character of a string split, using innerHTML, but it's showing nothing in alert box.
this is my code
Html
<html>
<head>
<title>JavaScript basic animation</title>
<script type="text/javascript">
</script>
<script type="text/javascript" src="myfunction_2.js"></script>
</head> <body>
<div id="target">w3resource </div>
<button onclick="shubham()">click</button>
</body>
</html>
Function
function shubham()
{
var x=document.getElementById('target').innerHTML;
var y=x.split('');
var z=y[0];
var m=y[9];
var n=y[1]
var last=y[y.length-1]
alert(last);
}
it works properly if I take var x as
var x='w3resource';
but i need to take x value as
var x=document.getElementById('target').innerHTML;
so what should i do for this???
You need to use textContent instead of innerHTML. innerHTML gets you the actual HTML markup, including the tag angled brackets (<>), whereas textContent will give you just the text.
var x=document.getElementById('target').textContent.trim();
Your code code exactly what it should do - it alerts a last character of #target element (which is a whitespace in your case).
If you changed <div id="target">w3resource </div> to <div id="target">w3resource</div> (removed the space at the end) the result would be 'e'.
If you want to find the very last text character you would have to use:
function shubham() {
// Element reference
const element = document.getElementById('target');
// Text without spaces at the beggining and the end
const text = element.innerText.trim();
// Get the last character
const lastCharacter = text[text.length - 1];
// Alert the last character
alert(lastCharacter);
}
<div id="target">w3resource </div>
<button onclick="shubham()">click</button>
I see that you have a space in the target div:
<div id="target">w3resource </div>
Hence the last character is a blank space, remove all the blank space and it should work, use the function below :
function shubham3()
{
var x=document.getElementById('target').innerHTML.replace(/ /g,'');
var y=x.split('');
var z=y[0];
var m=y[9];
var n=y[1]
var last=y[y.length-1]
alert(last);
}
Related
I am using a third-party plugin for javascript called QueryBuilder.
The problem is there is no way to trim the input after saved so the data is being saved like
testName=' test '
this is my javascript code, which is removing all spaces which is not what I want, I am trying to remove just space in the single quotes before and after all the text. Pretty much like a trim but the trim is not working so I need a regex to replace method
get_condition_sql__str = $.trim(get_condition_sql.sql);
get_condition_sql__clean = get_condition_sql__str.replace(/\s/g, '')
console.log(get_condition_sql__clean);
jQuery('.exception_conditions__sql').val(get_condition_sql__clean);
Lookahead for exactly one ' before the end of the string:
const input = `testName=' test '`;
const cleaned = input.replace(/ +(?=[^']*'$)/g, '');
console.log(cleaned);
There's only one word in the input, but if you need to preserve spaces between words inside the quotes, alternate between matching a ' on either side of spaces instead:
const input = `testName=' test test2 '`;
const cleaned = input.replace(/' +| +'/g, "'");
console.log(cleaned);
Please use this one for left space remove:
<script type="text/javascript">
var original_str3 = " This is a string"
//Strips all space to the left of the string
alert( original_str3.trimLeft() + ' <--- Without any spaces on the left' );
</script>
Or use this one for right space remove:
<script type="text/javascript">
var original_str4 = "This is a string "
//Strips all space to the right of the string
alert( original_str4.trimRight() + ' <--- Without any spaces on the right' );
For Remove space from both side character or string:
<script type="text/javascript">
var original_str2 = "S t r in g"
//Strips excessive white spaces i.e. retains only one space between each letter
var white_space_stripped_str = original_str2.replace(/\s+/g, ' ');
alert(white_space_stripped_str + ' <---- With exactly one space between each letter in case each letter has multiple spaces');
</script>
If any other are required then please let me know.
Example:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>
<p id="demo">"vSourceCountry = 'TEST'"</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var str = `testName=' test test2 '`;
var res = str .replace(/' +| +'/g, "'");
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Result:
Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:
testName='test test2'
Or You can use etc as per required:
https://www.w3schools.com/jsref/jsref_replace.asp
Not being too versed with JS yet, I've run into a weird issue where it seems like .replace() should be working but isn't.
I'm just trying to take a string (from an element ID) that has text + digits, replace the digits with a RegEx pattern, then replace the original text in that ID with the original text + new digits.
My HTML sample:
<html>
<body>
<p>Click the button to replace "Movies: 12344" with "Movies: 54321" in the paragraph below:</p>
<p id="demo">Movies: 1234!</p>
<button onclick="myFunction()">Try it</button>
</body>
</html>
My JS:
function myFunction() {
// Get all the text in #id=demo
var str = document.getElementById("demo");
// RegEx pattern to find ": <some digits>"
var pat = /\:\s?\d*/;
// Replace the digits
var res = str.replace(pat, ': 54321');
// Doesn't work (as a test) ...
//res = " hi"
// Replace the text in id=demo with original text + new digits.
str.innerHTML = res;
// Doesn't work (as a test) ...
//document.getElementById("demo").innerHTML = res;
}
At the moment, after clicking the button in the page, nothing happens.
This might help out a bit too:
https://codepen.io/stardogg/pen/aboREmL
In the same way you're setting the innerHTML in the last line of your function, innerHTML is also what you should be applying the replace on:
function myFunction() {
var str = document.getElementById("demo");
var pat = /\:\s?\d*/;
var res = str.innerHTML.replace(pat, ': 54321');
str.innerHTML = res;
}
<p>Click the button to replace "Movies: 12344" with "Movies: 54321" in the paragraph below:</p>
<p id="demo">Movies: 1234!</p>
<button onclick="myFunction()">Try it</button>
Your str variable is not equal to the text node within the element, but rather the element itself. To make str equal to the text within the element, try the following.
var str = document.getElementById("demo").innerText;
You need to extract text from the element before replacing.
//Replace the digits
var res = str.innerHTML.replace(pat, ': 54321');
I need help with how to code this program in javascript. The javascript code should load a character from a box and a number (N) from another box. When you press a button, N rows prints each one of those with N characters (same characters that are loaded are printed). Before printing, check that it is only available a character in the box where characters are to be entered.
code in html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="theText"></p>
<p id="theNumber"></p>
a charachter: <input type="charachter" id="theChar">
a number: <input type="number" id="theNbr">
<button onclick="printOut()">print out!</button>
<script type="text/javascript" src="script.js" ></script>
</body>
</html>
Code in Javascript:
function printOut(){
var theText = document.getElementById("theText").innerHTML;
document.getElementById("theText").innerHTML=
document.getElementById("theChar").value;
var theNumber = document.getElementById("theNbr").innerHTML;
document.getElementById("theNumber").innerHTML=
document.getElementById("theNbr").value;
var newText= theText;
var outPut;
for(i = 0; i<theNumber; i++){
newText =newText + theText;
}
newText = newText + "<br>";
for( i = 0; i< theNumber; i++){
outPut = outPut + newText;
}
document.getElementById("theText").innerHTML= outPut;
}
There are several issues in your code, even after the corrections you made after comments were made. Some of the more important:
Don't use innerHTML on an input element. It makes no sense. To get its value, use value.
Don't assign to document.getElementById("theNumber").innerHTML: it will replace any HTML you already had, and thus will remove the theNbr input. Any reference to it will fail with an error from now on.
Initialise your variables before reading from them. outPut is never initialised and so outPut + newText will give undesired results.
Although your can do this with for loops, there is a nice string method in JavaScript with which you can repeat a character or even a longer string: repeat.
Here is how it could work:
function printOut(){
var theNumber = document.getElementById("theNbr").value; // Don't use innerHTML
var theChar = document.getElementById("theChar").value;
var oneLine = theChar.repeat(theNumber) + "<br>";
var output = oneLine.repeat(theNumber);
document.getElementById("theText").innerHTML = output;
}
a charachter: <input type="charachter" id="theChar">
a number: <input type="number" id="theNbr">
<button onclick="printOut()">print out!</button>
<p id="theText"></p>
Problem:
After formatting text in a textarea, formatting is lost when copying to another textarea, whether by code or by mouse copy through ctrl-drag.
Details:
To prove the issue, I have a simple html page with no CSS, and a javascript function that formats the text by removing line breaks, using . I copy text from Notepad to my webpage's textarea1. I run the javascript function. This function replaces all carriage returns with "". The function runs correctly, with no errors. After running, all carriage returns have been removed from the text in textarea1. I can confirm they've been removed by running a function that copies the text from textarea1 to textarea2.
But, the weirdness comes next. After formatting textarea1, when I select all text and ctrl-drag (to copy) the text to textarea2, the original text is copied, with carriage returns back in place exactly where they were at before. The same happens if I copy-paste. What's going on?
Setup:
Win 7 machine, running IE9.
Code:
HTML...
<!DOCTYPE html>
<html>
<head>
<title>Text Editor</title>
<!--scripts-->
<script src="jquery-2.1.1.min.js"></script>
<script src="text_edit_test.js"></script>
</head>
<body>
<h1>Service Notes Text Editor</h1>
<textarea id="textarea1" cols="60" rows="11"></textarea>
<br>
<button type="button" id="buttonRemoveCR">Format Text</button>
<button type="button" id="buttonCopyText">Copy Text</button>
<br>
<textarea id="textarea2" cols="60" rows="30"></textarea>
</body>
</html>
... and javascript...
// make sure doc ready first
$(document).ready(function(){
//format Text
$("#buttonRemoveCR").click(function(){
var myText = "";
var myTextRes = "";
myText = $("#textarea1").html();
//remove all char returns
myTextRes = myText.replace(/\r/, "");
//change text in textarea1 so no carriage returns
$("#textarea1").html(myTextRes);
});
//copy Text
$("#buttonCopyText").click(function(){
var myText = "";
myText = $("#textarea1").html();
$("#textarea2").html(myText);
});
});
// make sure doc ready first
$(document).ready(function(){
//format Text
$("#buttonRemoveCR").click(function(){
var myText = "";
var myTextRes = "";
myText = $("#textarea1").val();
//remove all char returns
myTextRes = myText.replace(/(?:\r\n|\r|\n)/g, '')
//change text in textarea1 so no carriage returns
$("#textarea1").val(myTextRes);
});
//copy Text
$("#buttonCopyText").click(function(){
var myText = "";
myText = $("#textarea1").val();
console.log(myText);
$("#textarea2").val(myText);
});
});
Use x.val() to get the content of textarea x and x.val(text) to set the contents of textarea x -- textareas ignore their inner HTML.
I am trying to dynamically create a url slug when a user types into an input. Unwanted characters should be removed. Spaces should be replaced by hyphens and everything into lowercase. So if a user types "Ruddy's Cheese Shop" it should render "ruddys-cheese-shop".
This is what I have so far.
<input id="tb1" />
<div id="tb2"></div>
$('#tb1').keyup(function() {
var Text = $('#tb1').val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
$('#tb2').html($('#tb1').val(Text));
});
It almost works but I am new to js. Thanks
Your code but slightly improved.
$('#tb1').keyup(function() {
var text = $(this).val().toLowerCase();
text = text.replace(/[^a-z0-9]+/g, '-');
$('#tb2').text(text);
});
You don't need to find $('#tb1') element over and over again since you have a refference to it inside the function as $(this).
http://jsfiddle.net/jFjR3/
It looks ok except where you set the #tb2 value. I think you want:
$('#tb2').html(Text);
Of course, remember since you've called toLowerCase, you don't need to replace upper case chars. Rather a simpler regexp:
Text = Text.replace(/[^a-z0-9]+/g,'-');
If you also want to update the edit field as the user types, here's a full example. Note that it will only update #td2 when you start typing.
<html>
<head>
<script src="js/jquery.js" ></script>
<script language="javascript">
$(function() {
$('#tb1').keyup(function() {
var Text = $('#tb1').val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-z0-9]+/g,'-');
$('#tb2').html(Text);
$('#tb1').val(Text);
});
});
</script>
</head>
<body>
<input type="text" id="tb1" value="Ruddy's Cheese Shop" />
<div id="tb2"></div>
</body>
</html>
Looks like you need to run a couple of replaces i.e.
Text = Text.replace(/[\s]+/g,'-');
Text = Text.replace(/[^a-z_0-9\-]+/g,'');
That converts ruddy's Cheese Shop to ruddys-cheese-shop
Hope that helps