I'd like to be able to target (and then remove) this string of text:
[UPLOAD]any-possible_FILEname.ANY[/UPLOAD]
HTML:
var filenameRegex = new RegExp("\w\d\.");
$('.posts').contents().filter(':contains([UPLOAD])').filter(':contains([/UPLOAD])').filter(function() {
return filenameRegex.test($(this).text());
console.log('yep');
}).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="posts">
This is a forum post with lots of blabbing in it.
[UPLOAD]this-is-a-random-unknown-filename.jpg[/UPLOAD]
(Note the above always begins with [UPLOAD] and ends
with [/UPLOAD]. Also note that between these 'tags'
is 1 filename of some kind, such as an image or audio
or text file)
</span>
Thanks, much obliged.
var filenameRegex = /\[UPLOAD][\w\.\-]+\[\/UPLOAD]/gi;
$('.posts').filter(':contains([UPLOAD]):contains([/UPLOAD])').filter(function(i,e) {
return filenameRegex.test($(e).text());
}).each(function(i,e){
$(e).text($(e).text().replace(filenameRegex,''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="posts">
This is a forum post with lots of blabbing in it.
[UPLOAD]this-is-a-random-unknown-filename.jpg[/UPLOAD]
(Note the above always begins with [UPLOAD] and ends
with [/UPLOAD]. Also note that between these 'tags'
is 1 filename of some kind, such as an image or audio
or text file)
</span>
The regex you need is:
/\[UPLOAD\](.*)\[\/UPLOAD\]/gi
So your code should be like:
var filenameRegex = new RegExp("/\[UPLOAD\](.*)\[\/UPLOAD\]/gi");
$('.posts').contents().filter(':contains([UPLOAD])').filter(':contains([/UPLOAD])').filter(function(){
return filenameRegex.test($(this).text());
console.log('yep');
}).remove();
Not a regular expression, but this seems to do the trick:
var text = 'hello [UPLOAD]very[/UPLOAD] [UPLOAD]cruel[/UPLOAD] world';
var start = '[UPLOAD]';
var end = '[/UPLOAD]';
var index = text.indexOf(start);
while (index > -1)
{
var end_index = text.indexOf(end);
var removed_text = text.substring(index, end_index + end.length));
text = text.substring(0, index) + text.substring(end_index + end.length);
index = text.indexOf(start);
}
Related
Hi I have to find a missing number in an xml file. but I feel difficulty to find. Pls suggest some ideas.
Example
A file contains an <a> tag which include id i.e page-1,2... I need to find the missing numbers using jquery.
a.xml
<p>have a great <a id="page-1"/>day. How are you.</p>
<p><a id="page-2"/>Have a nice day.</p>
<p>How <a id="page-5"/>are you</p>
<p>Life is so exciting<a id="page-6"/></p>
My code
<script>
$(document).ready(function() {
$("#find").click(function(){
Fname = $("#myFile").val();
lpage = $("#lpage").val();
$.get(Fname, function(data){
var lines = data.split("\n");
if (lines.match(id="page-)) { //how to use regular exoreessi0n
alert("hi");
}
});
});
});
</script>
I'll take some assumptions regarding your input. Please add validations as necessary:
var lines = ['<p>have a great <a id="page-1"/>day. How are you.</p>',
'<p><a id="page-2"/>Have a nice day.</p>',
'<p>How <a id="page-5"/>are you</p>',
'<p>Life is so exciting<a id="page-6"/></p>'];
var sequences = [];
lines.forEach(function(line) {
// Not efficient but simple
// Let jQuery parse this string to object, so we won't need regexp
var obj = $(line);
// Assuming there's always A and ID attribute
var id = obj.find("a").attr("id").split("-");
// Assuming sequence is always last
sequences.push(parseInt(id[id.length - 1]));
});
sequences.sort();
// Again, inefficient, but will do the job
var last = sequences[sequences.length - 1];
for (var i = last; i >= 0; i--) {
if (sequences.indexOf(i) < 0) {
console.log(i + " is missing");
}
}
I know there are many similar questions posted, and have tried a couple solutions, but would really appreciate some guidance with my specific issue.
I would like to remove the following HTML markup from my string for each item in my array:
<SPAN CLASS="KEYWORDSEARCHTERM"> </SPAN>
I have an array of json objects (printArray) with a printArray.header that might contain the HTML markup.
The header text is not always the same.
Below are 2 examples of what the printArray.header might look like:
<SPAN CLASS="KEYWORDSEARCHTERM">MOST EMPOWERED</SPAN> COMPANIES 2016
RECORD WINE PRICES AT <SPAN CLASS="KEYWORDSEARCHTERM">NEDBANK</SPAN> AUCTION
I would like the strip the HTML markup, leaving me with the following results:
MOST EMPOWERED COMPANIES 2016
RECORD WINE PRICES AT NEDBANK AUCTION
Here is my function:
var newHeaderString;
var printArrayWithExtract;
var summaryText;
this.setPrintItems = function(printArray) {
angular.forEach(printArray, function(printItem){
if (printItem.ArticleText === null) {
summaryText = '';
}
else {
summaryText = '... ' + printItem.ArticleText.substring(50, 210) + '...';
}
// Code to replace the HTML markup in printItem.header
// and return newHeaderString
printArrayWithExtract.push(
{
ArticleText: printItem.ArticleText,
Summary: summaryText,
Circulation: printItem.Circulation,
Headline: newHeaderString,
}
);
});
return printArrayWithExtract;
};
Try this function. It will remove all markup tags...
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
Call this function sending the html as a string. For example,
var str = '<SPAN CLASS="KEYWORDSEARCHTERM">MOST EMPOWERED</SPAN> COMPANIES 2016';
var expectedText = strip(str);
Here you find your expected text.
It can be done using regular expressions, see below:
var s1 = '<SPAN CLASS="KEYWORDSEARCHTERM">MOST EMPOWERED</SPAN> COMPANIES 2016';
var s2 = 'RECORD WINE PRICES AT <SPAN CLASS="KEYWORDSEARCHTERM">NEDBANK</SPAN> AUCTION';
function removeSpanInText(s) {
return s.replace(/<\/?SPAN[^>]*>/gi, "");
}
$("#x1").text(removeSpanInText(s1));
$("#x2").text(removeSpanInText(s2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1 ->
<span id="x1"></span>
<br/>2 ->
<span id="x2"></span>
For more info, see e.g. Javascript Regex Replace HTML Tags.
And jQuery is not needed, just used here to show the output.
I used this little replace function:
if (printItem.Headline === null) {
headlineText = '';
}
else {
var str = printItem.Headline;
var rem1 = str.replace('<SPAN CLASS="KEYWORDSEARCHTERM">', '');
var rem2 = rem1.replace('</SPAN>', '');
var newHeaderString = rem2;
}
Trying to get the last part of the url in a pretty weird html structure. Don't ask why it's built that way. There is a very good reason behind it.
The html looks like this
<li class="lifilter"><input type="checkbox" class="filtercheck" id="Cheeks...">
<label for="Cheeks...">
Cheeks
</label>
</li>
and the js i'm trying to use
$('#Cheeks... label a').each(function(){
var lasturl = $(this).attr('href');
var urlsplit = url.split("/");
var finalvar = urlsplit[4];
$(this).addClass(finalvar);
});
edit: damn.. i can only post once every 90 minutes.
here is updated question with updated html
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="Cheeks...">
<label for="Cheeks...">
Cheeks
</label>
</li>
and the js code i'm trying to use (from a previous answer)
$('.lifilter').each(function(){
$(this).find(".filtercheck").next('label').find('a').each(function(){
var lasturl = $(this).attr('href');
var urlsplit = lasturl.split("/");
console.log(urlsplit);
var finalvar = urlsplit.pop();
console.log('Adding class: ' + finalvar);
$(this).addClass(finalvar);
});
});
OK, so it appears no one here attempted to try the solution here before posting.
First things first cheeks.... This is a tricky ID to find (You have to escape the periods). The label is also not part of the internal html where ID is cheeks..., so we need to find the adjacent element and look the a anchor tag you're looking for.
Here's the code:
$(document).ready(function() {
$('#Cheeks\\.\\.\\.').next('label').find('a').each(function(){
var lasturl = $(this).attr('href');
var urlsplit = lasturl.split("/");
console.log(urlsplit);
var finalvar = urlsplit.pop();
console.log('Adding class: ' + finalvar);
$(this).addClass(finalvar);
});
});
And here is a working jsfiddle with the solution.
keeping it simple like your code you'd do
finalvar = urlsplit[urlsplit.length-1];
in case you don't want the base url as a valid return then:
finalvar = ( urlsplit.length > 1 ? urlsplit[urlsplit.length-1] : "" );
replace "" with your preferred error/default return
you could also try to find the index of the last '/' and do a substring.
try this.
FIDDLE DEMO
var URI = 'www.example.com/sub1/sub2/sub3/',
parts = URI.split('/'),
lastPart = parts.pop() == '' ? parts[parts.length - 1] : parts.pop();
//RESULT : "sub3"
You can extract the last section of a path (i.e. everything after the last /) by using a regular expression:
text.replace(/.*\//g, "")
This will remove all of the text before a slash, as well as the slash itself. You'll also notice that your selector wasn't matching any elements; you're looking for labels nested within inputs, which doesn't match the html you posted (and isn't a valid DOM structure). An appropriate selector would be .lifilter label a, since the <label> is within the <li>.
$(function() {
setTimeout(function() {
$('.lifilter label a').each(function() {
// strip everything up to and including the last forward slash
var path = $(this).attr('href').replace(/.*\//g, "");
$(this).addClass(path);
});
}, 1500);
});
a.cheeks:after {
content: " (className = 'cheeks')";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li class="lifilter">
<input type="checkbox" class="filtercheck" id="Cheeks...">
<label for="Cheeks...">
Cheeks
</label>
</li>
if you want the last section of url for example activation code or id.You can try this.
var url = 'www.abc.com/code=12345',
parts = url.split('='),
lastPart = parts.pop()
//lastPart = 12345
I need to replace some part of text, e.g. mustache var {{myvar}}, on already loaded page.
Example html:
<html>
<head>
<title>{{MYTITLE}}</title>
</head>
<body>
<p><strong><ul><li>text {{TEXT}}</li></ul></strong></p>
{{ANOTHER}}
</body>
</html>
What's the problem? Use $(html).html(myrenderscript($(html).html()))!
It's ugly, slow and brokes <script> tags.
What do you want?
I want to get closest tag with {{}} and than render and replace.
Your researches?
Firstly, i tried: $('html :contains("{{")). But it returns <title>, <p>, <strong> .... But i need <title> and <li>.
Than i tried to filter them:
$('html :contains("{{")').filter(function (i) {
return $(this).find(':contains("{{")').length === 0
});
...but it WONT return {{ANOTHER}}. And that is my dead end. Your suggestions?
Using http://benalman.com/projects/jquery-replacetext-plugin/ you could do the following:
$('html *').replaceText(/{{([^}]+)}}/, function(fullMatch, key) {
return key;
}, true);
See http://jsfiddle.net/4nvNy/
If all you want to do is replace that text - then surely the following works (or have I mis-understood)
usage is as follows: CONTAINER (body) - replaceTExt (search term (I have built the function to always include {{}} around the term), (replace - this will remove the {{}} as well)
$('body').replaceText("MYTITLE","WHATEVER YOU WANT IT REPLACING WITH");
$.fn.replaceText = function(search, replace, text_only) {
return this.each(function(){
var v1, v2, rem = [];
$(this).find("*").andSelf().contents().each(function(){
if(this.nodeType === 3) {
v1 = this.nodeValue;
v2 = v1.replace("{{" + search + "}}", replace );
if(v1!=v2) {
if(!text_only && /<.*>/.test(v2)) {
$(this).before( v2 );
rem.push(this);
}
else this.nodeValue = v2;
}
}
});
if(rem.length) $(rem).remove();
});
};
You could avoid jQuery altogether if you wanted to with something like this:
<body>
<p><strong>
<ul>
<li>text {{TEXT}}</li>
</ul>
</strong></p>
{{ANOTHER}}
<hr/>
<div id="showResult"></div>
<script>
var body = document.getElementsByTagName('body')[0].innerHTML;
var startIdx = 0, endIdx = 0, replaceArray = [];
var scriptPos = body.indexOf('<script');
while (startIdx != 1) {
startIdx = body.indexOf('{{', endIdx) + 2;
if(startIdx > scriptPos){
break;
}
endIdx = body.indexOf('}}', startIdx);
var keyText = body.substring(startIdx, endIdx);
replaceArray.push({"keyText": keyText, 'startIdx': startIdx, 'endIdx': endIdx});
}
document.getElementById("showResult").innerHTML = JSON.stringify(replaceArray);
</script>
</body>
You can then do what you want with the replaceArray.
I have a definition list with associated variables and their values. (see fiddle too)
<dl id="myVars">
<dt class="var-name">%name%</dt>
<dd class="var-name">Joe Sample</dd>
<dt class="var-phone">%phone%</dt>
<dd class="var-phone">555-1212</dd>
</dl>
I also have a textarea that one can use any of the above variables within their text. For example:
<textarea>Hello %name%, is this still the right phone number: %phone%?</textarea>
Finally there's a preview div where one can see the interpreted text after the variables are replaced. Like so:
<div id="preview"></div>
Can you help me come up with an efficient way to use jQuery to show live previews at the same time it replaces variables with their values?
Here's a handy fiddle if you're up for helping: http://jsfiddle.net/XAzZr/
http://jsfiddle.net/NFtVc/
var subst = {}, // store substitutions in an object to eliminate DOM lookups
substRegex = /(.*)%(\S*)%(.*)$/i;
function defineSubst(){
$("#myVars dd").each(function(){
var cls = this.className.split(' '),
l = cls.length;
while (l--){
if (cls[l].indexOf('var-') == 0)
subst[cls[l].replace(/var-/, "")] = this.innerHTML;
}
});
}
function getSubst(key){
if (typeof subst[key] == "undefined")
return "[INVALID CODE]";
else
return subst[key];
}
function updatePreview(){
var txt = $('textarea').val().split(' '),
newTxts = [],
regex = /(.*)%(\S*)%(.*)$/i;
$.each(txt, function(){
var m = substRegex.exec(this);
if (m)
newTxts.push(m[1] + getSubst(m[2]) + m[3]);
else
newTxts.push(this);
});
$("#preview").text(newTxts.join(' '));
}
$('document').ready(defineSubst);
$('textarea').keyup(updatePreview);
$('textarea').on('keyup', function() {
var message = this.value.replace(/%(.*?)\S+/g, function(val) {
var elem = $('dt').filter(function() {
return $(this).text() == val;
});
return elem.length ? elem.next('dd').text() : '';
});
$('#preview').text(message);
});
FIDDLE