I have a Array like
text=['2','2<sup>2</sup>','3<sup>10</sup>'.......];
I want result like this
text=['2','22','310'......];
How can i get This using javascript
var optionTxt = (xmlDoc.getElementsByTagName('Option')[i].textContent ? xmlDoc.getElementsByTagName('Option')[i].textContent : xmlDoc.getElementsByTagName('Option')[i].text);
optionList[i] = $.trim(optionTxt);
You can use a .map operation for that and replace any non-digit with nothing using .replace():
text.map(function(item) {
return item.replace(/\D/g, '');
});
Since you're using jQuery you might also use their .map instead to fully benefit from cross (old) browser compatibility:
$.map(text, function(item) {
return item.replace(/\D/g, '');
});
Use .map() and .replace(). Try this:
var text=['2','2<sup>2</sup>','3<sup>10</sup>'];
text = $.map(text,function(i){
return i.replace( /[^\d.]/g,'');
});
console.log(text);
DEMO
Try jQuery html parsing:
var text = ['2', '2<sup>2</sup>', '3<sup>10</sup>'];
var out = [];
jQuery.each(text, function (si, str) {
var concat = '';
jQuery.each(jQuery.parseHTML(str), function (ei, el) {
concat = concat + el.textContent;
});
out.push(concat);
});
check out this fiddle: http://jsfiddle.net/9cV7M/
Related
I am trying to loop through some HTML elements, extract the content and set them as a const value with the index number like this...
jQuery('.myitems').each(function (index) {
const myitem + index = [jQuery(this).text()];
console.log(myitem + index);
});
This is not working, can anyone tell me the correct way to achieve?
You can use object instead of count. And your code will be broken.
See the following solution.
jQuery('.myitems').each(function (index) {
const count = {}
count[myitem + index] = [jQuery(this).text()];
console.log(count[myitem + index]);
});
Shouldnt you store the values in an array instead?
const myitem = [];
jQuery('.myitems').each(function (index) {
myitem[index] = jQuery(this).text();
console.log(myitem[index]);
});
You cannot do what you're attempting in JS. An alternative would be to populate an array with the values by using map():
var arr = $('.myitems').map(function() {
return $(this).text();
}).get();
If you still want to use the 'myitem' + index prefix on the values then you could instead use an object:
var obj = {};
$('.myitems').each(function(i) {
obj['myitem' + i] = $(this).text();
});
Here, I have first set constant and then on looping I have set value with index number. Currenlty , I have made output on console. You can check it. Let me know if you do not understand
const staff=[];
$('.staff').each(function(index){
staff[index]=$(this).text();
})
console.log(staff);
I have an array of postcodes that I have created by reading a text file. I would lik eto step through each item in the array and make it lowercase, and remove any whitespace. So far I have the following:
var postCodesCovered = new Array();
$.get('postcodes.txt', function(data){
postCodesCovered = data.split('\n');
});
$.each(postCodesCovered , function(){
$(this).toLowerCase().replace(/\s+/g, '');
});
This doesn't seem to do the trick though. Is it because I am not setting the values back to the array?
Since .get() is async you need to move your code in the success callback, and you don't need to use this.
var postCodesCovered;
$.get('postcodes.txt', function(data) {
postCodesCovered = data.split('\n');
$.each(postCodesCovered, function(index, value) {
postCodesCovered[index] = value.toLowerCase().replace(/\s+/g, '');
});
// Do something with the data here
});
#satpal is right - you need to process your list in the success callback. Each will iterate over the array items but you want to transform them into lowercase so map would be a better choice. Map takes an array and transforms each item returning a new array. See the jQuery.map docs for more info.
var postCodesCovered = [];
$.get('postcodes.txt', function(data) {
postCodesCovered = $.map(data.split('\n'), function(value, index) {
return value.toLowerCase().replace(/\s+/g, '');
});
});
ry this...
var postCodesCovered = new Array();
$.each(postCodesCovered , function(idx, val){
postCodesCovered[idx] = $(this).toLowerCase().replace(/\s+/g, '');
});
function convertArray(CapsArray){
lowcaseArray = [];
for (var i = 0; i <CapsArray.length; i++) {
lowcaseArray.push(CapsArray[i].replace(/\s+/g,"").toLowerCase());
}
return lowcaseArray;
}
The function above should do the job.
var YourLowCaseArray = convertArray(YourCapsArrayHere);
I have the following array:
etst,tset,tets,ttest,teest,tesst,testt,4est,test,dest
I want to delete the value of an input box from the array, here's what I'm trying:
var el = document.getElementById('searchInput').value; // this is "test"
var toSearchFor = eld.slice(0,10); // the array above
for(var i=0; i < toSearchFor.length; i++) {
toSearchFor[i] = toSearchFor[i].replace(/el/g, "");
}
It's simply not replacing "test" with ""
How can I do that?
You can use Array.filter (see MDN) to filter out the desired value:
var arr = 'etst,tset,tets,ttest,teest,tesst,testt,4est,test,dest'.split(',')
,val = 'test'
document.querySelector('#result')
.innerHTML = arr.filter(function (v) {return v != val});
<div id="result"></div>
A text field example in this jsFiddle
for global replacement of a string stored in a variable u need to create an instance of RegExp explicitly, like this:
var regex = new RegExp(el, "g");
then use it in replace function:
toSearchFor[i] = toSearchFor[i].replace(regex, "");
The problem with your code is in your regular expression: /el/g. This is trying to match the letters el, instead of whatever it's in the el variable. You could have done it using the RegExp construtor.
// ...
regexp = new RegExp(el); // No need to use 'g' here since you're looking for the whole word
toSearchFor[i] = toSearchFor[i].replace(regexp, "");
// ...
Here's another way of doing it:
var eld = ['etst','tset','tets','ttest','teest','tesst','testt','4est','test','dest'];
// var el = document.getElementById('searchInput').value;
var el = 'test';
console.log(eld);
var index = eld.indexOf(el);
if (index >= 0) {
eld[index] = '';
}
console.log(eld);
Here's the output:
["etst", "tset", "tets", "ttest", "teest", "tesst", "testt", "4est", "test", "dest"]
["etst", "tset", "tets", "ttest", "teest", "tesst", "testt", "4est", "", "dest"]
In this case, we're using Array.prototype.indexOf, which returns the first index at which a given element can be found in the array, so that we can access that element directly (if found).
I hope that helps!
var selValues = {};
selValues['234'] = $('#asd').val();
selValues['343'] = function () { var el = ''; $('#asd input[#type=checkbox]:checked').each(function() { el += $(this).val() + '|'; }); return el; } };
here's the explanation:
im creating a key-value array where it extracts different values from DOM objects. The last array that you see in the example actually tries to extract checked items in a checkbox list. I tried to delegate the loop and return a delimited string of all checked values, but it's not working.
A mapping is probably a better solution here:
var el = $('#asd input:checkbox:checked').map(function(){
return $(this).val();
}).get().join('|');
If I'm understanding your question correctly, the problem you are running up against is that you are merely storing a function in selValues['343'], not evaluating it.
You could try selValues['343'] = function () { var el = ''; $('#asd input[#type=checkbox]:checked').each(function() { el += $(this).val() + '|'; }); return el; } }(); (notice the parentheses at the end) which should evaluate your function and store the result in selValues['343'].
Seems to work for me: http://jsfiddle.net/HM4zD/
I have a div with id="a" that may have any number of classes attached to it, from several groups. Each group has a specific prefix. In the javascript, I don't know which class from the group is on the div. I want to be able to clear all classes with a given prefix and then add a new one. If I want to remove all of the classes that begin with "bg", how do I do that? Something like this, but that actually works:
$("#a").removeClass("bg*");
A regex splitting on word boundary \b isn't the best solution for this:
var prefix = "prefix";
var classes = el.className.split(" ").filter(function(c) {
return c.lastIndexOf(prefix, 0) !== 0;
});
el.className = classes.join(" ").trim();
or as a jQuery mixin:
$.fn.removeClassPrefix = function(prefix) {
this.each(function(i, el) {
var classes = el.className.split(" ").filter(function(c) {
return c.lastIndexOf(prefix, 0) !== 0;
});
el.className = $.trim(classes.join(" "));
});
return this;
};
2018 ES6 Update:
const prefix = "prefix";
const classes = el.className.split(" ").filter(c => !c.startsWith(prefix));
el.className = classes.join(" ").trim();
With jQuery, the actual DOM element is at index zero, this should work
$('#a')[0].className = $('#a')[0].className.replace(/\bbg.*?\b/g, '');
I've written a simple jQuery plugin - alterClass, that does wildcard class removal.
Will optionally add classes too.
$( '#foo' ).alterClass( 'foo-* bar-*', 'foobar' )
You don't need any jQuery specific code to handle this. Just use a RegExp to replace them:
$("#a").className = $("#a").className.replace(/\bbg.*?\b/g, '');
You can modify this to support any prefix but the faster method is above as the RegExp will be compiled only once:
function removeClassByPrefix(el, prefix) {
var regx = new RegExp('\\b' + prefix + '.*?\\b', 'g');
el.className = el.className.replace(regx, '');
return el;
}
Using 2nd signature of $.fn.removeClass :
// Considering:
var $el = $('<div class=" foo-1 a b foo-2 c foo"/>');
function makeRemoveClassHandler(regex) {
return function (index, classes) {
return classes.split(/\s+/).filter(function (el) {return regex.test(el);}).join(' ');
}
}
$el.removeClass(makeRemoveClassHandler(/^foo-/));
//> [<div class="a b c foo"></div>]
For modern browsers:
let element = $('#a')[0];
let cls = 'bg';
element.classList.remove.apply(element.classList, Array.from(element.classList).filter(v=>v.startsWith(cls)));
An approach I would use using simple jQuery constructs and array handling functions, is to declare an function that takes id of the control and prefix of the class and deleted all classed. The code is attached:
function removeclasses(controlIndex,classPrefix){
var classes = $("#"+controlIndex).attr("class").split(" ");
$.each(classes,function(index) {
if(classes[index].indexOf(classPrefix)==0) {
$("#"+controlIndex).removeClass(classes[index]);
}
});
}
Now this function can be called from anywhere, onclick of button or from code:
removeclasses("a","bg");
http://www.mail-archive.com/jquery-en#googlegroups.com/msg03998.html says:
...and .removeClass() would remove all classes...
It works for me ;)
cheers
I was looking for solution for exactly the same problem. To remove all classes starting with prefix "fontid_" After reading this article I wrote a small plugin which I'm using now.
(function ($) {
$.fn.removePrefixedClasses = function (prefix) {
var classNames = $(this).attr('class').split(' '),
className,
newClassNames = [],
i;
//loop class names
for(i = 0; i < classNames.length; i++) {
className = classNames[i];
// if prefix not found at the beggining of class name
if(className.indexOf(prefix) !== 0) {
newClassNames.push(className);
continue;
}
}
// write new list excluding filtered classNames
$(this).attr('class', newClassNames.join(' '));
};
}(fQuery));
Usage:
$('#elementId').removePrefixedClasses('prefix-of-classes_');
In one line ...
Removes all classes that match a regular expression someRegExp
$('#my_element_id').removeClass( function() { return (this.className.match(/someRegExp/g) || []).join(' ').replace(prog.status.toLowerCase(),'');});
I know it's an old question, but I found out new solution and want to know if it has disadvantages?
$('#a')[0].className = $('#a')[0].className
.replace(/(^|\s)bg.*?(\s|$)/g, ' ')
.replace(/\s\s+/g, ' ')
.replace(/(^\s|\s$)/g, '');
Prestaul's answer was helpful, but it didn't quite work for me. The jQuery way to select an object by id didn't work. I had to use
document.getElementById("a").className
instead of
$("#a").className
I also use hyphen'-' and digits for class name. So my version include '\d-'
$('#a')[0].className = $('#a')[0].className.replace(/\bbg.\d-*?\b/g, '');
(function($)
{
return this.each(function()
{
var classes = $(this).attr('class');
if(!classes || !regex) return false;
var classArray = [];
classes = classes.split(' ');
for(var i=0, len=classes.length; i<len; i++) if(!classes[i].match(regex)) classArray.push(classes[i]);
$(this).attr('class', classArray.join(' '));
});
})(jQuery);
The top answer converted to jQuery for those wanting a jQuery only solution:
const prefix = 'prefix'
const classes = el.attr('class').split(' ').filter(c => !c.startsWith(prefix))
el.attr('class', classes.join(' ').trim())
$("#element").removeAttr("class").addClass("yourClass");