My string is :<div>2</div><div>3</div><div>4</div><div>5</div><div><br></div>
I need to get 2,3,4,5, in an array using Javascript ie.anything between <div></div>
Whats the most elegant way to do this?
To match anything between <div> and </div>
var a, r=[];
while((s=str.indexOf("<div>"))!=-1){
e=str.indexOf("</div>");
a=str.substring(s+5, e);
if(a) r.push(a);
str=str.substr(e+6);
}
Another easier method
var r = str.match(/<div>.*?<\/div>/gi).map(function(i){
return i.replace(/<div>(.*?)<\/div>/gi, "$1");
});
If it was just digits (like in your initial question) use this
var str = "<div>2</div><div>3</div><div>4</div><div>5</div><div><br></div>";
var num = str.match(/\d+/g)
try the below code
var obj = $("div").map(function(index,value){
return $(this).html();
})
alert( "hi" +obj[0]);
http://jsfiddle.net/F9MQr/12/
For any value you could;
var s = "<div>2</div><div>3</div><div>4</div><div>5</div><div><br></div>";
var a = [];
$.each($(s).filter("div"), function() {
$(this).text() !== "" && a.push($(this).text());
});
alert(a);
(This would ignore empty divs & return X for <div>X<br/></div>)
Related
When I run this code:
var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
var foundUrl = foundUrlString[1];
I get an error if there are no matches on the page:
Result of expression 'foundUrlString' [null] is not an object
How can I get "false" when there are no matches instead of this error?
Going off of what you have, you could add a "truthy" check on the second line:
var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
var foundUrl = !!foundUrlString && foundUrlString[1];
That will leave foundUrl either as a matched string or false.
Check null to print false or true.
var savedPage = '';
var foundUrlString = savedPage.match( /og:url.*="(http.*\.com)/i );
var foundUrl = foundUrlString == null ? false : true;
console.log(foundUrl );
Here is an example with try and catch which may help you:
function regex(savedPage) {
try {
var foundUrlString = savedPage.match(/og:url.*="(http.*\.com)/i);
return foundUrlString[1];
} catch (error) {
return false;
}
}
var savedPage1 = '<link property="og:url" content="http://test.com/test">';
console.log('savedPage1',regex(savedPage1));
var savedPage2 = '<link content="http://test.com/test">';
console.log('savedPage2',regex(savedPage2));
You need to understand what's the purpose of String.prototype.match. The function match will return an array with the whole set of matched groups in your regexp. So, if you want to validate a string, the best way is using the function RegExp.prototype.test.
Use the function RegExp.prototype.test from regexp:
let savedPage = "EleFromStack";
console.log(/og:url.*="(http.*\.com)/i.test(savedPage));
I really need your help,
I would like to be able to check and see if a variable matches an array value and return true if it does.
ie.
var x = "ASFA"
var array = ["OTHER-REQUEST-ASFA", "OTHER-REQUEST-ASFB", "OTHER-REQUEST-ASFC"]
alert("true")
I was thinking of using this approach, but for the life of me, I cannot get it to return true, ideas?
function test() {
var arr = ["OTHER-REQUEST-ASFA","OTHER-REQUEST-ASFB","OTHER-REQUEST-ASFC"]
if ( $.inArray('ASFA', arr) > -1 ) {
alert("true")
}
}
Try as follows
var x = "ASFA"
var array = ["OTHER-REQUEST-ASFA", "OTHER-REQUEST-ASFB", "OTHER-REQUEST-ASFC"]
array.forEach(function(ele){
console.log(ele.includes(x));
})
Quick and easy with ES6 :
let x = "ASFA",
array = ["OTHER-REQUEST-ASFA", "OTHER-REQUEST-ASFB", "OTHER-REQUEST-ASFC"],
found = array.some(elem => elem.includes(x))
console.log(found)
I have the following fiddle:
jsfiddle
The function:
$('#testbutton').on("click", function(){
test();
});
function test()
{
var data = [];
data['article'] = "monablanko";
data['specialarticle'] = ["blanko", "bbsooel"];
var tmp = data['specialarticle'].join("|");
if( data['article'].match( /(tmp)/ ) )
{
$('#result').html("I found a match");
}
else
{
$('#result').html("I didn't found a match");
}
}
I didn't found a match with this function. Where is my error? The typeof tmp is string when i use
console.log(typeof tmp);
when i write
if( data['article'].match( /(blanko|bbsooel)/ ) )
then i find a match.
You're matching against the string literal "tmp", not against the value contained inside the variable tmp. Try it like this:
data['article'].match( new RegExp("(" + tmp + ")") )
eg: http://jsfiddle.net/4K8Km/
You need to create a RegExp to match your string before:
$('#testbutton').on("click", function(){
test();
});
function test(){
var data = [];
data['article'] = "monablanko";
data['specialarticle'] = ["blanko", "bbsooel"];
var tmp = new RegExp('('+data['specialarticle'].join("|")+')');
if( data['article'].match( tmp ) )
{
$('#result').html("I found a match");
}
else
{
$('#result').html("I didn't found a match");
}
}
Just one more tip: if you don't need to collect a match, but just to test if the string has that RegExp I would suggest to use test instead of match:
tmp.test(data['article']);
rather than
data['article'].match(tmp);
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/
I want to edit the value of an input field! To detail i want to delete the text that that is defined an an array from the input:
So if i have for example:
<input value="hello what is your">
and this array:
var arr = ["hello","is"];
I want to change the value of the input to:
<input value="what your">
How should i start? Thanks http://jsfiddle.net/rRXAG/
How should i start?
1) Iteration - Since you already use jQuery, try with $.each.
2) string.indexOf() - returns -1 if it is not present
var arr = ["hello","is"];
$.each(arr, function (i, j) {
var inTxt = $('input').val();
if (inTxt.indexOf(j) != -1) {
$('input').val(inTxt.replace(j, ''));
}
});});
JSFiddle
var val=document.getElementById("yourid").value;
for(var i=0;i<arr.length;i++){
val.replace(arr[i],"")
}
document.getElementById("yourid").value=val;
This regexp do the job :
$('input').first().val().replace(new RegExp(arr.join('|'), 'g'), '');
Fiddle : http://jsfiddle.net/rRXAG/2/
Assuming the values are words separated by spaces, you can do this:
1) Store the values into a map
var map = {};
for (var i in arr) map[arr[i]] = true;
2) Get the value from your input (it's a string) and filter it
var inputVal = $('input').first().val();
var newValue = inputVal.split(" ").filter(function(x) {
return !map[x];
}).join(" ");
// Set new value
$('input').first().val(newValue);