Contenteditable div
var1 = 'x';
var2 = someVar
Target
<span class="frag">var1 = 'x'</span>;
<span class="frag">var2 = someVar</span>;
JS
$('#board_code_dup').children().each(function (index, child) {
var text = $(child).html();
//HOW TO DO THIS RIGHT?
text = text.replace(/([A-Za-z0-9_]+\s*=\s*[A-Za-z0-9&'"]+)/g, '<span class="frag">$1</span>');
});
How would i use HTML entities " ' here instead of ' " so that i can properly wrap it?
This is what I've tried "$('#board_code_dup').text()" and split it on "\n" instead ..
It will convert entities behind the scene like quotes or double quotes in the source. This might match in reg-exp.
var result = $('#board_code_dup').text().split("\n").map(function (el, idx){
return el.replace(/\s*;\s*$/,'').replace( /(\w+\s*=\s*[\w&"']+)/g,'<span class="frag">$1</span>');
});
alert(result.join(''));
Js fiddle Here
I hope this will help ..
Related
Need to remove specific HTML tag span with class "notranslate", The following solution is removing all HTML tag from my text.
My expected result is: Deleted String: Adding string: Idea No.<p>d</p> value Details
var str = 'Idea No.<p>d</p> {{value}} Details';
var addStr = 'Adding string: ' + str.replace('{{', '<span class="notranslate">').replace('}}', '</span>');
console.log('Deleted String: ' + addStr.replace(new RegExp(/<\/?[\w\s="/.':;#-\/\?]+>/gi), ''));
If you really want to do it with a RegEx, you can use the below to strip any HTML span element which has the notranslate class. It takes into account the fact that you can have other properties on the element and multiple class names. As long as there is a <span> with class notranslate, it will strip the HTML tag and keep the content.
/<span.*?class=(?:"|"(?:[^"]*)\s)notranslate(?:"|\s(?:[^"]*)").*?>(.*?)<\/span>/
Working snippet:
let str1 = 'I want <span class="notranslate" data-xyz="whatever">this</span> to be removed.';
console.log('original:', str1);
console.log('modified:', str1.replace(/<span.*?class=(?:"|"(?:[^"]*)\s)notranslate(?:"|\s(?:[^"]*)").*?>(.*?)<\/span>/, "$1"));
let str2 = 'I want <span class="whatever notranslate another-class" data-xyz="whatever">this</span> to be removed.';
console.log('original:', str2);
console.log('modified:', str2.replace(/<span.*?class=(?:"|"(?:[^"]*)\s)notranslate(?:"|\s(?:[^"]*)").*?>(.*?)<\/span>/, "$1"));
If you can have multiple occurrences of that tag in the same string, you can add the g (global) flag.
/<span.*?class=(?:"|"(?:[^"]*)\s)notranslate(?:"|\s(?:[^"]*)").*?>(.*?)<\/span>/g
let str1 = 'I want <span class="notranslate" data-xyz="whatever">this</span> but <span class="notranslate" data-xyz="whatever">also this</span> to be removed.';
console.log('original:', str1);
console.log('modified:', str1.replace(/<span.*?class=(?:"|"(?:[^"]*)\s)notranslate(?:"|\s(?:[^"]*)").*?>(.*?)<\/span>/g, "$1"));
Parsing DOM is complex enough to not write it by hand.
If you can run it in a browser, here is the solution:
var str = 'Idea No.<p>d</p> {{value}} Details';
var addStr = 'Adding string: ' + str.replace('{{', '<span class="notranslate">').replace('}}', '</span>');
const dom = document.createElement('div');
dom.innerHTML = addStr;
const notranslate = dom.getElementsByClassName('notranslate');
for (let elem of notranslate) {
elem.remove();
}
console.log(dom.innerHTML);
To remove a specific HTML tag but to keep the innerHtml,
try this:
var str = 'Idea No.<p>d</p> {{value}} Details';
var addStr = 'Adding string: ' + str.replace('{{', '<span class="notranslate">').replace('}}', '</span>');
const dom = document.createElement('div');
dom.innerHTML = addStr;
const span = dom.getElementsByClassName('notranslate');
while(span.length) {
var parent = span[0].parentNode;
while(span[0].firstChild) {
parent.insertBefore( span[ 0 ].firstChild, span[0]);
}
parent.removeChild(span[0]);
}
console.log(dom.innerHTML); //Adding string: Idea No.<p>d</p> value Details
the method replace all tag because you use in RegExp the option 'gi' where 'gi' perform a global case-insensitive replacement. If you what replace a specific class you must define in regExp
I need to style the total cost for user added in a textarea.
I have this fragment of code:
$("#student_teacher_profile_for_teaching_amount").keyup(function(e) {
var new_str, price, regex, str;
regex = /[0-9]+\.[0-9]{1,2}|[0-9]/;
str = $(this).val();
console.log(str);
price = str.match(regex);
if(price) {
if( $("#to_teach_ammount").length > 0 ) {
$("#to_teach_ammount").html(price[0]);
} else {
new_str = str.replace(regex, "<span id='to_teach_ammount'>" + price[0] + "</span>");
$(this).val(new_str);
}
$("#to_teach_total").val(price[0]); #this is and hiddent input filed
}
});
As a result of it I get:
some text before numbers <span id='to_teach_ammount'>2</span>
in my textarea.
How can I convert this into raw HTML?
This is not possible with a common <textarea> element, which only accepts plain text. You will have to use a (rich-text)-plugin, for example with jQuery. Have a look here: http://www.strangeplanet.fr/work/jquery-highlighttextarea/
The to_teach_total should not be a textarea. Instead it should be an element which expects html
Then use $(this).html(new_str) to set html
This html() method can also be passed a function which can take old html as parameter and return a new string to be set as new html
I have a string in the below non-escaped format in a HTML page:
<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>
What I need is to use jQuery/JavaScript to replace that string with just the link "SomeThing".
I have looked at some examples in StackOverflow, but they don't seem to work. I'm just getting started with jQuery and JavaScript, so would appreciate any help here.
Any ideas?
Try html() and text() in jquery to decode:
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var decoded = $('<div />').html(str).text();
alert($(decoded).text());
See Fiddle demo
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var helper = document.createElement('p');
// evaluate as HTML once, text now "<a href..."
helper.innerHtml = str;
// evaluate as HTML again, helper now has child element a
helper.innerHtml = helper.innerText;
// get text content only ("SomeThing")
alert(helper.innerText);
Here is a possible starting point.
Hope this gets you started!
function parseString(){
var str = '<a href="http://somesite/product?page=blahk&id=EA393216&tabs=7,0&selections=quarter:Q2+2013^&wicket:pageMapName=wicket-2\">SomeThing</a>';
var begin = str.indexOf('\">',0)+2; //--determine where the opening anchor tag ends
var end = str.indexOf('</a>',0); //--determine where the closing anchor tag begins
var parsedString = str.substring(begin,end); //--grab whats in between;
/*//--or all inline
var parsedString = str.substring(str.indexOf('\">',0)+2,str.indexOf('</a>',0));
*/
console.log(parsedString);
}
parseStr();
I have a HTML string ( not DOM element ) like :
<p>This is a sample dataa<p>
<img src="Randomz" alt="Randomz Image">Randomz is the name of the image</img>
I need to append a <span class="spellerror"></span> to the words that have problem and that too only the Textual contents need to be checked and appended .
<p>This is a sample dataa<p>
<img src="Randomz" alt="Randomz Image"><span class="spellerror"> Randomz </span> is the name of the image</img>
My problem is that this is a mix of HTML and regex . Is it possible:
To make this some kind of a DOM element and then work on it ?
Or is there a regex way to achieve this.
I dont want to touch the attributes and if I modify Text contents , how do I publish it back ...because I need some HTML inserted there .
I dont love this solution, but it works:
'<img src="Randomz" alt="Randomz Image">Randomz is the name of the image</img>'
.match(/<[^>]+>|[^<]+|<\/[^>]+>/g)
.map(function (text, index) {
if (index === 1) {
return text.replace(/(Randomz)/, '<span class="spellerror">$1</span>');
} else {
return text;
}
})
.join('');
The regex splits into opening tag, innerText, closing tag.
Then iterates on all members, if its the innerText, it replaces with desired text
Then joins.
Im stil trying to think of something less round-about but thats all i got
Use some form of templating:
String.prototype.template = String.prototype.template ||
function (){
var args = Array.prototype.slice.call(arguments)
,str = this
;
function replacer(a){
var aa = Number(a.substr(1))-1;
return args[aa];
}
return str.replace(/(\$\d+)/gm,replacer);
};
var thestring = [ '<p>This is a sample dataa</p><img src="Randomz"'
,' alt="Randomz Image">$1Randomz$2 '
,'is the name of the image</img>'].join('')
,nwString = theString.template('<span class="spellerror">','</span>');
Please consider the following HTML <pre> element:
This is some
example code which
contains tabs
I would like to replace all of the tab characters with four non-breaking space characters in HTML (i.e. ). I have tested the above pre element with JavaScript for the presence of tab characters as follows:
$('pre').ready(function() {
alert(/\t/.test($(this).text()));
});
But it is always returned false. Can anyone tell me the correct process by which to replace tab spaces from the source code to HTML NBSPs? The tabs have been added by Komodo Edit, and are visible when viewing the source.
You can do it like this:
$('pre').html(function() {
return this.innerHTML.replace(/\t/g, ' ');
});
That will loop through all pre elements on the page and call the function for each of them. jQuery's html function uses the return value of the function we give to replace the content of each element. We're using String#replace to replace all (note the g flag on the regexp) tab characters in the HTML string with four non-breaking spaces.
Live example
It removes line breaks, extra spaces and line breaks:
function removeNewlines(str) {
//remove line breaks from str
str = str.replace(/\s{2,}/g, ' ');
str = str.replace(/\t/g, ' ');
str = str.toString().trim().replace(/(\r\n|\n|\r)/g,"");
console.log(str);
}
Demo:
function removeNewlines(str) {
//remove line breaks from str
str = str.replace(/\s{2,}/g, ' ');
str = str.replace(/\t/g, ' ');
str = str.toString().trim().replace(/(\r\n|\n|\r)/g,"");
console.log(str);
}
$('#acceptString').click(function() {
var str = prompt('enter string','');
if(str)
removeNewlines(str)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' value='Enter String' id='acceptString' />
Try this:
var tab = RegExp("\\t", "g");
document.getElementById("text").value =
document.getElementById("text").value.replace(tab,' ');