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
Related
Let's say I have an HTML document with the following body:
<style>
.highlighted {
color: red;
background-color: yellow;
}
</style>
<article>My text in an element</article>
I have the challenge to style the i letter from the in word inside the <article> tag with javascript, and I'm required to do it by it's index [8].
So far I can only think of starting with this...
<script>
const article = document.querySelector('article').innerText
console.log(article[8]);
</script>
Expected output:
<article>My text <span class="highlighted">i</span>n an element</article>
// Console
>>>> "i"
...although I've never tried anything like this before, so I'm kinda lost with the following steps.
I supose I need to insert a <span> tag by this index, but I'm not sure how I would set the closing </span> tag or update the DOM.
What would be a good way to achieve this kind of styling?
//get text of article
const article = document.querySelector('article').innerText;
//find index of word 'in'
const index = article.indexOf('in');
//opening and closing tags
const openingTag = '<span style="color:red">'
const closingTag = '</span>'
//insert tags into article
const newHTML
= article.slice(0, index)
+ openingTag + 'in' + closingTag
+ article.slice(index + 2);
document.querySelector('article').innerHTML = newHTML;
This code styles the first occurrence of the word "in" by setting the text color to red. If you want to do something else, change the style attribute of the opening tag.
article.slice(0, index) returns everything before the word "in." In your example, this would evaluate to 'My text '. article.slice(index + 2) returns everything after the word "in" because "in" is 2 letters long. In your example, this would evaluated to ' an element'. When all the strings are concatenated together, the result is 'My text <span style="color:red">in</span> an element'.
const HIGHLIGHT_IDX = 8;
const article = document.querySelector('article').innerText;
const words = article.split(' ');
let highlightCheck = words[0].length;
let wordToHighlight = words[0].length >= HIGHLIGHT_IDX && '0';
let wordIdx = 1;
while (!wordToHighlight) {
highlightCheck += 1 + words[wordIdx].length;
if (highlightCheck >= HIGHLIGHT_IDX) {
wordToHighlight = wordIdx;
} else {
wordIdx += 1;
}
}
words[wordToHighlight] =
`<span class="highlight">${words[wordToHighlight]}</span>`;
document.querySelector('article').innerText = words.join(' ');
I have this string:
s='data-id="a1429883480588" class="privateMessage" #zaza
data-id="a1429883480589" class="privateMessage" #zaza2
data-id="a1429883480598" class="privateMessage" #zaza3'
My goal is to capture the what's between : data-id=" and " to have results:
[a1429883480588, a1429883480589, a1429883480598]
I tried with
var splitted = s.match(/data-id="(\w)+(?=")/g)
But this also captures data-id=" and "
Any idea on how to write this regex ?
It must be done with JS since it is nodeJS function !
If you're happy that the string will always be well formed and not mangled up. Here's one that'll do it:
var s = '<span data-id="a1429883480588" class="privateMessage">#zaza</span> ';
s += '<span data-id="a1429883480589" class="privateMessage">#zaza2</span> ';
s += '<span data-id="a1429883480598" class="privateMessage">#zaza3</span>';
s.match(/data-id="\w+"/g).map(function(attributeAndValue) {
return attributeAndValue.split('"')[1];
})
The concerns raised above about using RegEx to parse HTML are valid but more for HTML in the wild.
Here's the cheerio equivalent, just for reference or whatever
var cheerio = require('cheerio');
var markup = '<span data-id="a1429883480588" class="privateMessage">#zaza</span> <span data-id="a1429883480589" class="privateMessage">#zaza2</span> <span data-id="a1429883480598" class="privateMessage">#zaza3</span>';
var $ = cheerio.load('<div>'+markup+'</div>');
var ids = Array.prototype.map.call($('[data-id]'), function(e) {
return $(e).attr('data-id');
});
console.log(ids);
// [ 'a1429883480588', 'a1429883480589', 'a1429883480598' ]
Here is the JS code in which I am splitting a String using ":" . So a String given by:
Habit #1: Have you established dedicated business checking account(s)?
Would split into:
[0]=Habit #1
and
[1]=Have you established dedicated business checking account(s)?
Now I want to apply CSS to [0].
titles=document.getElementsByClassName("title");
for(var i=0;i<titles.length;i++){
titles[i].innerHTML.split(":")[0].style.cssText="color:aqua;";
}
Any modification you guys suggest to the existing code?
You can replace the fist part of the string like so:
var titles=document.getElementsByClassName("title");
for(var i=0;i<titles.length;i++){
var blueFoo = titles[i].innerHTML.split(":")[0];
var text = titles[i].innerHTML;
var newHTML = text.replace(blueFoo,'<span style = "color:blue">' + blueFoo + '</span>');
titles[i].innerHTML = newHTML;
}
For example:
var titles=document.getElementsByClassName("title");
titles= "<span>" + titles;
titles=titles.replace(":", ":</span">);
document.getElementsByClassName("title").innerHtml = titles;
I think this could work.
I think you have to wrap the first characters to the ":" with a <span class=""> and give them a css class.
<p><span class="blue">Habit #1:</span> Have you ... </p>
Mike
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 ..
I got some html formatted in the following way:
[Title|<a class="external" href="http://test.com">http://test.com</a>]
From these texts I'd like to create links using "Title" as the text and "http://test.com" as link. How can I best do this in prototype?
Pure RegExp:
var ProperLink=WierdString.replace(/\[([^|]+)\|(<[^>]+>)[^<]+[^\]]+\]/,'$2$1</a>')
in the context you provided:
function convert(id){
$(id).innerHTML=$(id).innerHTML.replace(/\[([^|]+)\|(<[^>]+>)[^<]+[^\]]+\]/g,'$2$1</a>');
}
convert('testdiv');
Here is a regex that will retain the original attributes of the anchor tag while doing the replacement:
var link = "[Title|<a class=\"external\" href=\"http://test.com\">http://test.com</a>]";
var pattern = /\[([^|]+)\|([^>]+.?)[^<]*(<\/a>)\]/;
link.replace(pattern, "$2$1$3"));
The output is:
<a class="external" href="http://test.com">Title</a>
Without prototype: http://jsfiddle.net/JFC72/ , you can use prototype to make it simpler.
var myStr = "[THIS IS TITLE|http://test.com]";
document.getElementById('testdiv').innerHTML = getLink(myStr);
function getLink(myStr)
{
var splitted = myStr.split("|http");
var title = splitted[0].substring(1);
var href = splitted[1].substring(0,splitted[1].length-1);
return "<a href='http" + href + "'>" + title + "</a>";
}
var dummyDiv = document.createElement('div');
dummyDiv.innerHTML = '[Title|<a class="external ...';
var parts = dummyDiv.innerText.slice(1, -1).split('|');
// parts[0] is the text, parts[1] is the URL