I am trying to recognize character inside div and add to all the matches class.
Example :
> Kapetown > China Town >London > Washington
I want to recognize the character > and give all of them class
I tried to do this
if (sign.indexOf("$") >= 0) {
//remove the sign
}
Here is a trick you can use:
var a = '> Kapetown > China Town >London > Washington' //get the text from document here
a = a.split('>');
a = a.join('<span class="myClass">></span>');
Now you can replace "a" in your document.
This is just a trick you can use in your case. Maybe this will help you.
I assume that there is only text inside the targeted div
$(document).ready(function() {
// get the target element
var breadcrumbs = $('#breadcrumbs')
// get all text of that element. Note: this will remove all
// HTML tag and get only the text
var str = breadcrumbs.text()
// a regEx to find all occurrences of ">" sign
// and wrap them with span.myClass
var strHtml = str.replace(/\>/g, "<span class='myClass'>></span>");
// push the replaced string back to the targeted element
breadcrumbs.html(strHtml)
})
.myClass {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.2/jquery.min.js"></script>
<div id="breadcrumbs">> Kapetown > China Town >London > Washington</div>
If I understand your problem correctly, then you have a particular HTML like so:
<div id="abc">
> Capetown > China > London > Washington
</div>
and you want it to be lets say something like this:
<div id="abc">
<span class="some-class">></span> Capetown <span class="some-class">></span> China <span class="some-class">></span> London <span class="some-class">></span> Washington
</div>
Then by vanilla javascript you could achieve this via Regex. Here is how I would do it if the HTML was like the example I proposed:
let content = document.getElementById('abc').textContent.replace(/>/g, '<span class="some-class">></span>');
document.getElementById('abc').innerHTML = content;
What I am doing here is that with document.getElementById('abc').textContent, I am getting the text content that is inside <div id="abc">...</div> and I am storing this text content in a mutable variable content.
Then I used the String.prototype.replace method of JavaScript to replace the required character (in our case it is the ">" character). The String.prototype.replace method accepts two parameters: a pattern and the replacement string. read about the replace method here
The character I want to select is ">". So using Regex the pattern I want to match is />/. Now just using this expression will only match the first instance of ">". So I give it a global parameter to match all occurrences of ">" by />/g.
Now we want to give it a class. So I decide to use the inline HTML element <span> to avoid any changes in the DOM layout. Now for the replacement substring, I use <span class="some-class">></span>. The > is the HTML code for the ">" sign. Lets include these two parameters in our String.prototype.replace method as content.replace(/>/g, '<span class="some-class">></span>');
When executed, the variable content now contains our required character with a class. Next, I replaced the content of <div id="abc">...</div> by the content variable with document.getElementById('abc').innerHTML = content;. I used the .innerHTML property because we have included some HTML in our replacement string.
If this is what you wanted then hope this helps.
use can use {'>'} for react
example:
<div className='row'>
{route[0]} {'>'} {route[1]} {'>'} {route[2]}
</div>
where route = ["home","products","productID"];
Related
I need to search a <div> of a specific class for a simple text system, then store the text.
Basically, there will be a div, and inside the div there might be some text like:
[ALERT](TEXT TO STORE HERE)
I'd like to search a div for the ALERT tag, then store any text inside the () under a variable if it exists, and push an alert to the console if it's found.
However, while I can easily find the first part, [ALERT], I cannot figure out how to find the whole string, or store the containing text. I think it should end up something like:
var alerttext = $("#result").find("[ALERT](.)")=(function()
{
return $(this).html();
}).get();
However, that seems pretty far off, and definitely isn't working.
Edit: The html would resemble:
<div id="bbb" class=""><p id="aaa">text test text
[ALERT](TEXT TO STORE HERE)
More text down here
</p></div>
Try using .text() , String.prototype.replace() with RegExp /(\n.+\()|(\).+\n+\s+$)/g to replace input string up to ( , from ) to end of input , remove newline, space characters at beginning and end of matched string
var arr = [];
$("#bbb").text(function(i, text) {
if (text.indexOf("[ALERT]") >= 0) {
var match = text.replace(/(\n.+\()|(\).+\n+\s+$)/g, "");
arr.push(match);
console.log(arr);
};
return text
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="bbb" class="">
<p id="aaa">text test text [ALERT](TEXT TO STORE HERE) More text down here
</p>
</div>
Edit: It looks like we identified the solution to this problem via the comments -- which is achieved by getting value of the .outerHTML property. However, it still appears that at least Firefox and Chrome "normalize" original source code when outerHTML is used. For example, outerHTML of
<div id = "a"> <!-- string is 14 characters long //-->
still returns
<div id="a"> <!-- string is 12 characters long //-->
Apparently, the problem would be considered solved if the formatting of the resulting string would match that of the original HTML source code. Ah! Why must outerHTML adjust the original value?
--- Having said this: ---
I'm looking for a solution to get full text of a clicked HTML tag.
Starting point examples (note intentional, legal but mangled formatting):
<div id = "a" style ="color: blue ;">text</div>
// Returns: div
var doc = document.getElementById("id").tagName;
// Returns: array of attribute name/value pair (without = or ")
var attrs = document.getElementById("id").attributes;
How would we go about generating the following text string, when element #a is clicked:
<div id = "a" style= "color: blue ;">
I seem to have not found a solution for this as of yet.
What's this for?
Ultimately, the goal is to determine the length in characters of the arbitrary contents of a tag. Assuming it can be edited in any way that produces acceptable HTML output. For example, the two cases below should return:
<div id=a style="color:blue"> // 28
<div id = "a" style= "color: blue ;"> // 36
Counting is the easy part. It's getting the actual string of that tag, just as it appears in the source code, that is the problem.
Have you tried this?
document.getElementById('a').outerHTML
But this doesn't work in every browser i guess
Use outerHTML to get the full tag and then strip out everything after the open tag.
var openTag = document.getElementById("a").outerHTML.split(">")[0] + ">";
This seems to do what you want:
http://jsfiddle.net/abalter/c3eqnLrc/
html:
<div id="a" class="find-my-length" style="color:blue">First One</div>
<div id="a " class="find-my-length" style= "color: blue ; " > Second One </div >
JavaScript:
$('.find-my-length').on('click', function () {
var htmlString = $(this).prop('outerHTML');
alert(htmlString + " has " + htmlString.length + " characters.");
});
Note: The one thing that doesn't get counted is spaces between attributes. Spaces within attributes are counted.
From: Get selected element's outer HTML
What about: prop('outerHTML')?
var outerHTML_text = $('#item-to-be-selected').prop('outerHTML');
And to set:
$('#item-to-be-selected').prop('outerHTML', outerHTML_text);
I am looking to build a regular expression that will select a single word out of all text between HTML tags. I am looking for the occurrence of the word anywhere but inside HTML tags. The issue is that the word I am looking to match may occur in the class or id of a tag - I would only like to match it when it is between the tags.
Here is further clarification from my comment:
I am looking for a regex to use in a loop that will find a string in another string that contains HTML. The large string will contain something like this:
<div class="a-class"<span class="some-class" data-content="some words containing target">some other text containing target</span>
I want the regex to match the word "target" only between the tags, not within the tag in the data-content attribute. I can use:
/(\btarget)\b/ig
to find every instance of target.
http://jsfiddle.net/techsin/xt1j2cj8/3/
here is one way to do it.
var cont = $(".cont")
html = cont.html(),
word = "Lorem";
word = word.replace(/(\s+)/, "(<[^>]+>)*$1(<[^>]+>)*");
var pattern = new RegExp("(" + word + ")", "gi");
html = html.replace(pattern, "<mark>$1</mark>");
html = html.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/, "$1</mark>$2<mark>$4");
$(".cont").html(html);
If the word can be present anywhere i.e. even as a class name or id name then here is what you can do,
Take <html> as the parent element and access all the contents within it using innerHTML, now you can find any word as follows,
<html id="main">
<div>
<p class="yourword">
</p>
</div>
</html>
var str = document.getElementById("main").innerHTML;
var res = str.match(/yourword/gi);
alert(res);
The above string matches the word "yourword" from the entire document.
Here is a demo which selects the string "sub".
I am trying to achieve this:
I have this code:
<h1>Search results for "<span>photoshop</span>"</h1>
And, I have another code like this in the same page:
<p>Photoshop is the best photo editor in the world</p>
With jQuery or pure JavaScript, I want to get the word within the span which changes dynamically, store it in a variable, and wrap every other 'photoshop' word in the document with a 'highlighted' class. How can I do this?
You can use a regular expression and jQuery's html() function to find and replace all occurances of a word with that word wrapped in a span.
<h1>Search results for "<span id="search">Photoshop</span>"</h1>
var theWord = $('#search').text(),
patt=new RegExp('\\b(' + theWord + ')\\b', 'gi');
$('body').html($('body').html().replace(patt,'<span class="highlight">$1</span>'));
(use 'gi', if you want it to be global and case insensitive)
http://jsfiddle.net/EBWQX/2/
and if you can't give the span an id, maybe selecting $('h1 span') would be specific enough (depending on your code)
You can try to use jQuery Highlight Plugin.
Example there:
HTML:
<input onkeyup="setNewSearch(this);" />
<h1>Search results for "<span id="search"></span>"</h1>
<!-- text -->
Javascript:
function setNewSearch(input){
var value = $(input).val();
$("#search").html(value);
$("body").unhighlight();
$("body").highlight(value);
}
I'm trying to use JS to replace a specific string within a string that contains html tags+attributes and styles while avoiding the inner side of the tags to be read or matched (and keep the original tags in the text).
for example, I want <span> this is span text </span> to be become: <span> this is s<span class="found">pan</span> text </span> when the keyword is "pan"
I tried using regex with that ..
My regex so far:
$(this).html($(this).html().replace(new RegExp("([^<\"][a-zA-Z0-9\"'\=;:]*)(" + search + ")([a-zA-Z0-9\"'\=;:]*[^>\"])", 'ig'), "$1<span class='found'>$2</span>$3"));
This regex only fails in cases like <span class="myclass"> span text </span> when the search="p", the result:
<s<span class="found">p</span>an class="myclass"> s<span class="found">p</span>an text</s<span class="found">p</span>an>
*this topic should help anyone who seeks to find a match and replace the matched string while avoiding strings surrounded by specific characters to be replaced.
As thg435 say, the good way to deal with html content is to use the DOM.
But if you want to avoid something in a replace, you can match that you want to avoid first and replace it by itself.
Example to avoid html tags:
var text = '<span class="myclass"> span text </span>';
function callback(p1, p2) {
return ((p2==undefined)||p2=='')?p1:'<span class="found">'+p1+'</span>';
}
var result = text.replace(/<[^>]+>|(p)/g, callback);
alert(result);