How to change the value of innerText at a particular index? - javascript

I am trying to change the string displayed in the frontend by using a function in javascript.
let displayword = document.getElementById("displayword”)
console.log(displayword.innerText) //apple
Say, I want the change the letter “l” to something else say “i” but keep the rest of the letters unchanged how do I go around this?
Things I have tried
displayword.innerText[3] = “i” // -----does nothing----
I am confused why the above code using index does nothing, while the below does something
dash.innerText += “i” //applei
Extra question: Why does the above code using =+ change the formatting of the innerText? I want to keep the large font but it changes to regular font of the element (here I am using h1).
Thank you:)

You should look at the String documentation, especially String.slice and String.substring
In many languages, Strings can't be modified directly. Instead you "change" it by creating a new string composed of parts of the original.
As for how you'd do it in your case:
var text = displayWord.innerText;
text = text.slice(0, 3) + 'i' + text.slice(4) // apple -> appie
displayWord.innerText = text;
[Edited code slightly]

displayword.innerText = displayword.innerText.replace(oldCharacter, newCharacter);
To replace all occurrences:
displayword.innerText = displayword.innerText.replaceAll(oldCharacter, newCharacter);

Related

Javascript - regex replace string [duplicate]

I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;

Set value of textarea at desired line

So I can append text to a textarea using this method
document.getElementById('myArea').value += msg;
This tacks the new input onto the end of the current input.
Suppose the textarea already contains text. Suppose also that using "=" instead of "+=" and inputting the values textarea already had along with the new ones is not a possible solution in this context
How would one input new text to this textarea on the correct line and in the correct position with respect to the text that is already in place?
Here is a YouTube video demonstrating the problem
https://www.youtube.com/watch?v=GpwEuI3_73I&feature=youtu.be
UPDATE:
Instead of sending one letter at a time, I sent the whole textarea each time a key is pressed. Obviously more computationally taxing, but that's the only solution I have right now. I am still interested in hearing any better solutions if you have one!
I'm assuming you send only the last character typed (as in your original approach), and it is stored in a variable named "newChar".
Take this as pseudo-code, although I hope it does not require many changes to actually work:
// deserialize the text of the target textearea
var txt = targetTextarea.text;
var txtAsArray = txt.split(/\r?\n/);
var txtLine = txtAsArray[cursorRowNum];
// write the new character in the right position (but in memory)
txtLine = txtLine.substr(0, cursorColNum) + newChar + txtLine.substr(cursorColNum);
// now serialize the text back and update the target textarea
txtAsArray[cursorRowNum] = txtLine;
txt = txtAsArray.join("\n");
targetTextarea.text = txt;
A reference used was: How in node to split string by newline ('\n')?
Regarding performance, there is no additional network activity here, and we are accessing the DOM only twice (first and last line). Remember than accessing the DOM is around 100 times slower than plain variables in memory as shown by http://www.phpied.com/dom-access-optimization/ .
That "txt = txtAsArray.join("\n");" might need to be "txt = txtAsArray.join("\r\n");" on Windows. Detecting if you are in one or the other is explained at How to find the operating system version using JavaScript as pointed by Angel Joseph Piscola.
Hi this will add text to existing text in textarea
i have try that
var msg = "Hi How are you ?";
document.getElementById('myArea').value += msg;

Slip input type value live using javascript

i'm trying to live edit a text box value so that the result will be split every two character,
adding a column and starting from some default character.
what i have till now is this code, that obviously doesn't work:
$('#textboxtext').keyup(function (){
var text = $("#textboxtext").val();
//$(text).attr('maxlength', '12');
var splitted = text.match(/.{2}|.{1,2}/g);
var result = ("B8:27:EB:" + splitted.join(':'));
});
i need the live split and the default character inside the textbox but i really don't know where to start...
From your code, it seems like you're trying to create a text box that has some very specific behavior. It looks like it needs to format its value in such a way that it always begins with certain 'prefix' of B8:27:EB:, and every subsequent pair of characters is is separated by a :. This is actually a very complex behavior and you have to consider a number of different interactions (e.g. what happens when the user attempts to delete or modify the prefix). I usually try to avoid such complex controls if possible, however here is a quick implementation:
$('#textboxtext').keyup(function (e){
var prefix = "B8:27:EB:",
text = $(this).val(),
splitted, result;
if (text.indexOf(prefix) == 0)
text = text.substr(9);
else if (prefix.indexOf(text) == 0)
text = "";
text = text.replace(/:/g, '');
splitted = text.match(/.{1,2}/g) || [];
result = prefix + splitted.join(':');
$(this).val(result);
});
Demonstration
Type inside the text box and see what happens. Also note, there are all kinds of interaction that this implementation doesn't account for (e.g. right-clicking and pasting into the text box), but it's a start.

How to find and replace text in between two tags in HTML or XML document using jQuery?

I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;

Javascript debugging - script works with hard coded variable, not with getElementById('id').value

I'm trying to debug some javascript I wrote and can't figure out why it's not working. If I hard code the variables it works fine, but if I use document.getElementById('id').value to get the variable it fails.
The example below works fine but as soon as I un-comment the commented lines it doesn't. Printing the variables before and after the second section they seem to be identical.
Really don't get what's going on. Maybe I just need to sleep on it, but if anyone's got suggestions that would be great!
roof_width = 5;
roof_depth = 3;
panel_width = 2;
panel_depth = 1;
panel_power = 200;
roof_margin = 0.100;
panel_gap = 0.05;
roof_width = document.getElementById('roof_width').value;
roof_depth = document.getElementById('roof_depth').value;
// panel_width = document.getElementById('panel_width').value;
// panel_depth = document.getElementById('panel_depth').value;
panel_power = document.getElementById('panel_power').value;
// roof_margin = document.getElementById('roof_margin').value;
panel_gap = document.getElementById('panel_gap').value;
Are you trying to add numbers that are in text boxes? Because of the way JavaScript's variable typing system works (combined with the overloading of the + operator), 2 + 2 === 4 (adding numbers) but '2' + '2' === '22' (string concatenation). Try changing the lines to, for example:
panel_width = parseFloat(document.getElementById('panel_width').value);
or alternatively:
panel_width = Number(document.getElementById('panel_width').value);
This will ensure that JavaScript treats the numbers as numbers rather than as strings.
JavaScript parameters can't be called in the same way that you're calling HTML elements. In order to call
document.getElementById('roof_margin').value;
you need to assign 'roof_margin' to an HTML form element.
Pherhaps you have multiple dom elements with the same id? Remember the dom element ID must be unique. I suggest you to use jquery for interacting javascript with html.
Make sure your code is in an onload function. Otherwise the elements may not have been loaded into the DOM yet.
window.onload = funciton(){/* code here */};

Categories