Replacing text in an input box of a webpage (with defined ID) - javascript

I am trying to fill up all the input fields of a webpage (having input IDs ending with txtValue) which are filled with the word ‘dog’ to be replaced with the word ‘cat’.
I have tried this code, but it isn’t working. Kindly help me to solve this. Thank you in advance.
const ta = document.querySelectorAll("[id$='txtValue']");
const str = ta.value.replace("dog","cat");
ta.value = str
console.log(ta.value,"change to" ,str)

querySelectorAll returns an array which needs to be iterated over.The replace method returns the modified string without changing the original.So,the following should work.
ta.forEach(elem => elem.value = elem.value.replace("dog","cat"))

querySelectorAll() returns a list. So you need to iterate the list to set each value.
const ta = document.querySelectorAll("[id$='txtValue']");
for (let i = 0; i <= ta.length; i++){
const str = ta[i].value.replace("dog","cat");
ta[i].value = str
}
console.log("finished");

This code is the answer to the question.
const ta = document.querySelectorAll("[id$='txtValue']");
for (let i = 0; i <= ta.length; i++){
const str = ta[i].value.replace("dog","cat");
ta[i].value = str
}
console.log("finished");

Related

JS Array Find and Replace?

I have a regular expression happening that searching for all the capitals in a document. It gathers them and puts them into an array no problem.
The issue I am having is I want to replace the items in that array to include a span around each item that was captured in the array and then display the updated result. I've tried a variety of things.
I am at a complete loss. Any help is appreciated. Here was my last attempt
var allCaps = new RegExp(/(?:[A-Z]{2,30})/g);
var capsArray = [];
var capsFound;
while (capsFound = allCaps.exec(searchInput)) {
capsArray.push(capsFound[0]);
}
//for(var x = 0; x < capsArray.length; x++){
//var test = ;
capsArray.splice(0, '<span style="color:green">'+ capsArray +'</span>');
//}
}
You can't convert an entire array's elements like that using splice - you can use .map instead:
capsArray = capsArray.map(c => '<span style="color:green">' + c + '</span>');
Do you need the results in an array? If not, you can wrap all caps in a str using a modified regex:
str.replace(/([A-Z])/g, '<span>$1</span>')
example:
'A--B--C' becomes '<span>A</span>---<span>B</span>---<span>C</span>'
if the array is needed for whatever reason:
str.split(/[^A-Z]+/g).map(x => `<span>${x}</span>`)
example:
'A--B--C' becomes ['<span>A</span>', '<span>B</span>', '<span>C</span>']
Thanks to everyone for the help.
Heres my final solution for anyone else that gets lost along the way
var allCaps = new RegExp(/(?:[A-Z]{2,30})/g);
var capsArray = [];
var capsFound;
while (capsFound = allCaps.exec(searchInput)) {
capsArray.push(capsFound[0]);
}
if(capsArray.length > 0){
resultsLog.innerHTML += "<br><span class='warning'>So many capitals</span><br>";
searchInput = document.getElementById('findAllErrors').innerHTML;
searchInput = searchInput.replace(/([A-Z]{3,30})/g, '<span style="background-color:green">$1</span>');
document.getElementById('findAllErrors').innerHTML = searchInput;
}
else {
resultsLog.innerHTML += "";
}

How to remove a part of all strings in an array in javascript?

I want split array value .
for example
gUser[1] = CAR.BENZ.CCLASS.1962
gUser[2] = CAR.PORSCHE.911.2001
I want get string only BENZ.CLASS.1962 and PORSCHE.911.2001
How to split array value on java script?
#update.
not always CAR string.
so, not use substring.
You can use map to access each string in array then use replace. Use a regex to match string before '.' and replace only the first match, like this:
var gUser = ['CAR.BENZ.CCLASS.1962', 'CAR.PORSCHE.911.2001'];
var gUserModified = gUser.map(function(v){
return v.replace(/[^\.]+\./, '');
});
console.log(gUserModified);
Split it with dot then slice it and join it with dot
var gUser =[];
gUser[1] = "CAR.BENZ.CCLASS.1962";
gUser[2] = "CAR.PORSCHE.911.2001";
console.log(gUser[1].split('.').slice(1).join('.'));
console.log(gUser[2].split('.').slice(1).join('.'));
From your question, it's not clear if the array is a string array
If it is a string array you can do:
ES6+: gUser.map((user)=>{return user.split("CAR.")[1]})
ES5: gUser.map(function(user){return user.split("CAR.")[1]});
The below code is not tested but should probably work, with maybe minor tweaks
var splitStr = ''
var correctCarArr = []
for(let i = 0; i < gUser.length; i++){
splitStr = gUser[i].split('.')
let temp = ''
for(let j = 1; j < splitStr.length; j++){
temp += splitStr[j]
}
correctCarArr.push(temp)
}
var gUser = [];
gUser[1] = "CAR.BENZ.CCLASS.1962";
var gu1 = gUser[1].split(".");
gu1.shift();
console.log(gu1.join("."));
So here is the way without using any regex by only using string and array methods.
const gUser = ['CAR.BENZ.CCLASS.1962', 'CAR.PORSCHE.911.2001', 'XYZAB.PORSCHE.YSA.2021']
for (let i = 0; i < gUser.length; i++) {
console.log('Required String: ', gUser[i].split('.').slice(1).join('.'));
}
What we do is, we split the string into parts where . is encountered.
gUser[0].split('.') returns ['CAR', 'BENZ', 'CCLASS', '1962']
Later when slice(1) is called, the zeroth element of array is chopped off and will return ['BENZ', 'CCLASS', '1962']
And finally using join('.'), we merge the array elements to a single string with a . between each element, which returns BENZ.CCLASS.1962
Hope this helps! :)
Its easier split then shift the array to remove the first item like this:
gUser = ["CAR.BENZ.CCLASS.1962"];
var benz = gUser[0].split(".");
benz.shift();
alert(benz.join('.'));
There are other options from shift like slice(1) but In terms of performance, shift is apparently faster https://jsperf.com/shift-pop-vs-slice/4
Something Like This
`for(let index = 0; index < gUser.length; index++) {
console.log(gUser[index].split('.').splice(0, 1).join('.'));
}`
I haven't tested it. Please check and let me know

Javascript: How to re-arrange content display of text field?

I have a text field (not a date field) who contain simply a value such "2013-08-27" and my goal would be to reverse the order and get "27-08-2013". So is matter to re-arrange the content but I don't have enough javascript knowledge. I tried using some "date" variable but without success much probably because my field is not a date field.
The html related to the field look like this:
<input type="text" value="2013-08-27" name="my_field" id="my-field" readonly="">
If you can give me an example of code based of this:
var my_field = document.getElementById('my_field');
thank
PS: I precise I don't have access to html of this field because is located to a remote server. I can only interact by adding code in a JS file planned for that. The field have also a "readonly" property because is not planned for be modified.
This code should do the trick:
var revert = function(str) {
var parts = str.split("-");
var newArr = [];
for(var i=parts.length-1; p=parts[i]; i--) {
newArr.push(p);
}
return newArr.join("-");
}
var replaceValueInInputField = function(id) {
var field = document.getElementById(id);
field.value = revert(field.value);
}
var replaceValueInDomNode = function(id) {
var el = document.getElementById(id);
var value = el.innerHTML, newValue = '';
var matches = value.match(/(\d{4})-(\d{2})\-(\d{2})/g);
for(var i=0; m=matches[i]; i++) {
value = value.replace(m, revert(m));
}
el.innerHTML = value;
}
replaceValueInInputField("my-field");
replaceValueInDomNode("my-field2");
jsfiddle http://jsfiddle.net/qtDjF/2/
split('-') will return an array of number strings
reverse() will order array backwards
join("-") will join array back with '-' symbol
var my_field_value = document.getElementById('my_field').value;
my_field_value.split('-').reverse().join("-");
You can use the split function.
var my_field = document.getElementById('my_field').split("-");
the var my_field will be an array of string like : "YYYY,mm,dd"
and then you can re-arrange it in the order you want.
Try this
var date = document.getElementById("my-field").value;
//alert(date);
var sp = date.split("-");
alert(sp[2]+"-"+sp[1]+"-"+sp[0]);
With Jquery
var parts =$('#my-field').val().split("-");
$('#my-field').val(parts[2]+"-"+parts[1]+"-"+parts[0]);
Simple regex:
var res;
test.replace(/(\d\d\d\d)-(\d\d)-(\d\d)/,function(all,a,b,c){res=c+"-"+b+"-"+a;});
JSFiddle: http://jsfiddle.net/dzdA7/8/
You could try splitting the string into array and inverting it's items in a loop:
var my_field = document.getElementById('my_field').value.split("-"),
length = my_field.length,
date = [];
for(i = length - 1; i >= 0; i--){
date.push(my_field[i]);
}
console.log(date.toString().replace(/,/g,"-"));

function to change argument to another sign

I dynamically create this list element and information a user has typed in shows up in it when a button is clicked 'info' is text and shuld show as it is but 'grade' is a number that i want to convert to another sign with the function changeNumber() but I am new to javascript and cant figure out how to make this function, can anyone give a suggestion or point me in the right direction?
var list = $("#filmlista");
var list_array = new Array();
function updateFilmList()
{
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = list_array[0][1];
var element = '<li class="lista">' + list + '<span class="grade">'+ changeNumber(grade) +'</span></li>';
list.append(element);
}
should I use innerHTML? not shure I understand how it works? and how do I use the replace method if I have to replace many different numbers to the amount of signs the number is?
for example if the number is 5 it should show up as: *****, if number is 3 show up as: *** and so on
Here's some code that should do the trick:
Add this function into your script.
function changeNumber(number) {
var finalProduct = "";
for (var i = 0; i < number; i++) {
finalProduct += "*";
}
return finalProduct;
}
Replace the updateFilmsList with this code.
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = changeNumber(list_array[0][1]);
var element = '<li class="lista">' + list + '<span class="grade">'+ grade +'</span></li>';
list.append(element);
It looks like you're trying to do something like PHP's str_repeat. In that case, take a look at str_repeat from PHPJS
There are options other than a loop:
function charString(n, c) {
n = n? ++n : 0;
return new Array(n).join(c);
}
charString(3, '*'); // ***
You can use innerHTML to set the text content of an element provided none of the text might be mistaken for markup. Otherwise, set the textContent (W3C compliant) or innerText (IE proprietary but widely implemented) property as appropriate.

How to remove a null element in jquery?

I have an application in which i am storing values in localstorage. By default my first value is null due to which i am getting error to run the code so i want to remove the first element and continue the processes. can anyone please help me how to remove first element from list?
Piece of my code is below:
var str = localStorage.getItem("appidlist");
var mySplitResult = str.split(",");
for(var i = 0; i < mySplitResult.length; i++) {
if (.....) {
.
.
}
}
where str returns null,1,2,3,.....
I hope my question is clear can anybody help me.
This should also work:
var str = localStorage.getItem("appidlist");
var mySplitResult = str.split(",");
mySplitResult.splice(0, 1);
You can use .shift().
mySplitResult.shift()
Instead of uing the shift() function, I would suggest you to create a function that return a new clean array. This will solve even the case where there are more than one (and in any postion) null value.
You can use this solution
This should do the trick:
var str = localStorage.getItem("appidlist");
var mySplitResult = str.split(",").splice(1); // Remove the first item.
for(var i = 0; i < mySplitResult.length; i++) {
// Stuff
}

Categories

Resources