I have a set of urls that i need to get a specific part of . The format of the url is :
http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg
I need to get the 1234567 bit and store that in a var.
Well you can do splits
"http://xxx.xxxxx.com/xxxx/xxxx/1234567_1.jpg".split("/").pop().split("_").shift()
or a regular expression
"http://xxx.xxxxx.com/xxxx/xxxx/1234567_1.jpg".match(/\/(\d+)_\d+\.jpg$/).pop()
You should be able to get it to work with your JSON string by checking the URL with a function. Something like this should work:
function checkForMatches(str) {
var res = str.match(/.*\/(.*)_1.jpg/);
if(res) {
output = res[res.length-1];
} else {
output = false;
}
return output;
}
$.get("test.php", function (data) {
// now you can work with `data`
var JSON = jQuery.parseJSON(data); // it will be an object
$.each(JSON.deals.items, function (index, value) {
//console.log( value.title + ' ' + value.description );
tr = $('<tr/>');
tr.append("<td>" + "<img class='dealimg' src='" + value.deal_image + "' >" + "</td>");
tr.append("<td>" + "<h3>" + value.title + "</h3>" + "<p>" + value.description + "</p>" + "</td>");
//tr.append("<td>" + value.description + "</td>");
tr.append("<td> £" + value.price + "</td>");
tr.append("<td class='temperature'>" + value.temperature + "</td>");
tr.append("<td>" + "<a href='" + value.deal_link + "' target='_blank'>" + "View Deal</a>" + "</td>");
myvar = checkForMatches(value.deal_link);
if(myvar == false) {
myvar = value.deal_link; //if no matches, use the full link
}
tr.append("<td>" + "<a href='" + myvar + "' target='_blank'>" + "Go To Argos</a>" + "</td>");
$('table').append(tr);
});
});
Earlier, more basic examples.
You can use a regular expression to find the match.
Something like this would work:
var str = "http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg";
var res = str.match(/.*\/(.*)_1.jpg/);
alert(res[1])
If you wanted to go a little further with it, you could create a function and pass the strings you wanted to test, and it would return the matched value if found, or boolean false if no matches exist.
Something like this would work:
function checkForMatches(str) {
var res = str.match(/.*\/(.*)_1.jpg/);
if(res) {
output = res[res.length-1];
} else {
output = false;
}
return output;
}
alert(checkForMatches("http:\/\/xxx.xxxxx.com\/xxxx\/xxxx\/1234567_1.jpg"))
alert(checkForMatches("this is an invalid string"))
You can see it working here: https://jsfiddle.net/9k5m7cg0/2/
Hope that helps!
var pathArray = window.location.pathname.split( '/' );
to split 1 / 2/ 3/ 4...
So to get path 2 it would be:
var setLocation = pathArray[1];
Well This should do
function getLastFolder(){
var path = window.location.href;
var folders =path.split("/");
return folders[folders.length-1]);
}
Here's the idea: take everything that comes after the final / character, and then take everything within that substring that comes before the first _ character.
var getUrlTerm = function(url) {
var urlPcs = url.split('/');
var lastUrlPc = urlPcs[urlPcs.length - 1];
return lastUrlPc.split('_')[0];
}
You can attribute the url to an 'A' element and use javascript's built in methods to make your life easier:
var parser = document.createElement('a');
parser.href = "YOUR URL HERE";
var fileName = parser.pathname.split('/').pop();
var code = fileName.split('_')[0];
code will have the value you want.
I would use a regular expression and sense it seems you are looking for numbers you can do the regex filter for that.
var path = window.location.pathname,
regFilter = /\d*/g,
filter = regFilter.exec(path);
The regular expression \d narrows your filter search to only look for digits. And the * grabs the group of digits.
Your result is in the filter var. The only thing about this is that the exec returns an array with your original string and the returned result which will be at the 1 index so you'll have to grab it from there like so.
filter[1];
Related
The code is used in a HTML document, where when you press a button the first word in every sentence gets marked in bold
This is my code:
var i = 0;
while(i < restOftext.length) {
if (text[i] === ".") {
var space = text.indexOf(" ", i + 2);
var tekststykke = text.slice(i + 2, space);
var text = text.slice(0, i) + "<b>" + tekststykke + "</b>" + text.slice(i + (tekststykke.length + 2));
var period = text.replace(/<b>/g, ". <b>");
var text2 = "<b>" + firstWord + "</b>" + period.slice(space1);
i++
}
}
document.getElementById("firstWordBold").innerHTML = text2;
}
It's in the first part of the code under function firstWordBold(); where it says there is an error with
var space1 = text.indexOf(" ");
Looks like you're missing a closing quote on your string, at least in the example you provided in the question.
Your problem is the scope of the text variable. In firstWordBold change every text to this.text, except the last two where you re-define text
Also, if you want to apply bold to the first word this is easier...
document.getElementById('test-div-2').innerHTML = '<b>' + firstWord + '</b>' + restOftext;
It now works for me, with no errors and it applies bold to the first word.
Here's how the function ended up,
function firstWordBold() {
console.log('bolding!');
var space1 = this.text.indexOf(' ');
var firstWord = this.text.slice(0, space1);
var restOftext = this.text.slice(space1);
document.getElementById('test-div-2').innerHTML = '<b>' + firstWord + '</b>' + restOftext;
}
To make every first word bold, try this...
function firstWordBold() {
let newHTML = '';
const sentences = this.text.split('.');
for (let sentence of sentences) {
sentence = sentence.trim();
var space1 = sentence.indexOf(' ');
var firstWord = sentence.slice(0, space1);
var restOftext = sentence.slice(space1);
newHTML += '<b>' + firstWord + '</b>' + restOftext + ' ';
}
document.getElementById('test-div-2').innerHTML = newHTML;
}
One last edit, I didn't notice you had sentences ending with anything other that a period before. To split on multiple delimiters use a regex, like so,
const sentences = this.text.split(/(?<=[.?!])\s/);
I need to break a string apart after certain characters.
document.getElementById("result").innerHTML = Monster + "<p id='vault" + loop + "'> || HP: " + HP + "</p>" + " || Defense: " + Def + " || Attack: " + ATK + " || Can it Dodge/Block: " + DB + " || Can it retaliate: " + RET + " || Initative: " + INT + " || Exp: " + MEXP + " <input type='submit' class='new' onclick='Combat(" + loop + ")' value='FIGHT!'></input>" + "<br><br>" + A;
function Chest(id){
window.open('LootGen.html', '_blank');
}
function Combat(id){
document.getElementById("C").value = document.getElementById("vault" + id).innerHTML;
}
When this runs the value that results is:
|+HP:+20
However I only want '20' part,now keep in mind that this variable does change and so I need to use substrings to somehow pull that second number after the +. I've seen this done with:
var parameters = location.search.substring(1).split("&");
This doesn't work here for some reason as first of all the var is an innher html.
Could someone please point me in the write direction as I'm not very good at reading docs.
var text = "|+HP:+20";
// Break string into an array of strings and grab last element
var results = text.split('+').pop();
References:
split()
pop()
using a combination of substring and lastIndexOf will allow you to get the substring from the last spot of the occurrence of the "+".
Note the + 1 moves the index to exclude the "+" character. To include it you would need to remove the + 1
function Combat(id){
var vaultInner = document.getElementById("vault" + id).innerHTML;
document.getElementById("C").value = vaultInner.substring(vaultInner.lastIndexOf("+") + 1);
}
the code example using the split would give you an array of stuff separated by the plus
function Combat(id){
//splits into an array
var vaultInner = document.getElementById("vault" + id).innerHTML.split("+");
//returns last element
document.getElementById("C").value = vaultInner[vaultInner.length -1];
}
I'm having a small problem with a regexp pattern. I don't have regexp knowledge, so I couldn't solve it.
I have this text:
var text = "this (is) some (ran)dom text";
and I want to capture anything between (). So after following this tutorial I came up with this pattern:
var re = /(\(\w*\))/g;
which works fine. But what I want to do now is replace the found matches, or rather modify. I want to wrap the found matches with a span tag. So I used this code:
var spanOpen = '<span style="color: silver;">';
var spanClose = '</span>';
text.replace(re, spanOpen + text.match(re) + spanClose);
even though the code works, I don't get the result I want. It outputs:
as HTML
this <span style="color: silver;">(is),(ran)</span> some <span style="color: silver;">(is),(ran)</span>dom text
as text
this (is),(ran) some (is),(ran)dom text
You can check the example in fiddle. How can I fix this?
The code in fiddle:
var text = "this (is) some (ran)dom text";
var re = /(\(\w*\))/g;
var spanOpen = '<span style="color: silver;">';
var spanClose = '</span>';
var original = "original: " + text + "<br>";
var desired = "desired: this " +spanOpen+"(is)"+spanClose+ " some " +spanOpen+"(ran)"+spanClose+ "dom text<br>";
var output = "output: " + text.replace(re, spanOpen + text.match(re) + spanClose);
var result = original + desired + output;
document.body.innerHTML = result;
If the title is wrong or misleading, I'll change it.
The .replace() method can take a function as the 2nd parameter. That will come in handy here.
var output = "output: " + text.replace(re, function(match){
return spanOpen + match + spanClose
});
The function will be called for each individual match.
You can also use '$&' in your replace string to reference each match
var output = "output: " + text.replace(re, spanOpen + '$&' + spanClose);
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
text.match(re) is returning an array of the result, so what you can do is loop this array and replace your string with each items, like this:
var matches = text.match(re);
var output = "output: " + text;
for (var i = 0; i < matches.length; i++)
{
output = output.replace(matches[i], spanOpen + matches[i] + spanClose);
}
See this FIDDLE
I've got a piece of code that duplicates a <table> but in the process changes id's. It took hours but I eventually got this to happen with:
var lookFor = 'url' + parseInt(uploadCount);
++uploadCount; //used to create a unique id
var replaceWith = 'url'+parseInt(uploadCount);
var regex = new RegExp(lookFor, 'g');
var tableHTML = '<table class="user-url-table" style="opacity:0;" id="url' + uploadCount + '">' + $('table.user-url-table').first().html().replace(regex, replaceWith) + '</table>';
$(tableHTML).insertAfter($('table.user-url-table').last());
However, the following doesn't work:
var lookFor = 'url' + parseInt(uploadCount);
var tableHTML = '<table class="user-url-table" style="opacity:0;" id="url' + uploadCount + '">' + $('table.user-url-table').first().html() + '</table>';
++uploadCount;
var replaceWith = 'url'+parseInt(uploadCount);
var regex = new RegExp(lookFor, 'g');
tableHTML = $('table.user-url-table').first().html().replace(regex, replaceWith);
But shouldn't they do exactly the same job....? The first piece of code surely just does everything in one line, whereas the second forms the <table> and then changes all instances of the id in it.
There are two errors on the second code. First, when you do tableHTML = $('table.user-url-table').first().html().replace(regex, replaceWith); on the last line, you throw away the preparation you did. You override the value of tableHTML.
The second error is that the result is not appended to the document, like you did with insertAfter in the first code.
To make if work, replace the last line with $('table.user-url-table').after(tableHTML.replace(regex, replaceWith));. This will insert tableHTML with the replaced id's after the first table.
Another way, much simpler, of doing the same thing is this:
var firstTable = $("#url1 tbody").html();
var result = "";
for (i = 2; i < 10; i++) {
result += '<table class="user-url-table" style="opacity:0.2;" id="url'
+ i + '">' + firstTable.replace("url1", "url" + i) + '</table>';
}
$("#url1").after(result);
Fiddle: http://jsfiddle.net/bortao/ydEPr/
I am trying to implement a search box that will search a particular play (AJAX file) for any instances of the word, if the word is found it then outputs that line. My problem is that if no results are found of the word instead of continuing to show the entire play it outputs the last line of the play only.
My function:
function searchResults(query) {
var temp = "\\b" + query + "\\b";
var regex_query = new RegExp(temp, "gi");
var currentLine;
var num_matching_lines = 0;
$("#mainOutput").empty();
$("LINE", current_play_dom).each(function () {
var line = this;
currentLine = $(this).text();
matchesLine = currentLine.replace(regex_query, '<span class="query_match">' + query + '</span>');
if ( currentLine.search(regex_query) > 0 ) {
num_matching_lines++
$("#mainOutput").append("<br /><p class='speaker_match'>"+ $(line).parent().find('SPEAKER').text() +"</p>");
$("#mainOutput").append("<p class='act_match'>"+ $(line).parent().parent().parent().children(':first-child').text()+"</p>");
$("#mainOutput").append("<p class='scene_match'>"+ $(line).parent().parent().children(':first-child').text() +"</p>");
$("#mainOutput").append("<p>" + matchesLine + "</p>");
$("#mainOutput").append("<br>");
}
});
$("#mainOutput").append("<p>" + matchesLine + "</p>");
$("#sideInfo").append("<p>Found " + query + " in " + num_matching_lines + " lines</p>");
}
Also as a side question is there a neater way to do this:
$(line).parent().parent().parent().children(':first-child')