find phone numbers and give link using javascript - javascript

I am trying to give link to phone numbers in a page using javascript. SO Post
is helpful but it also update contents in input box, href, src etc. How to update phone numbers that are not tag attribute and text inside <a> tag
var regex = /((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}/g;
var text = $("body:first").html();
text = text.replace(regex, "$&");
jsfiddle

Since you need to update phone numbers that are not tag attributes and not the content inside an anchor tag, you can change the regexp to use negative lookahead.
This would be the regex -
((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}(?!([^<]*>)|(((?!<a).)*<\/a>))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Modified part
Explaining the regex -
The first part of the regex is the same.The second part is a negative lookahead. If the regexp inside the (?! ) matches, then that is not the required string. So we need to match the tag attributes and the innerHTML of anchor tag.
For values inside tag attributes, this is the regexp
([^<]*>)
For content in anchor tag -
(((?!<a).)*<\/a>)
Placing both the regexps above inside the negative lookahead allows you to negate the strings that the above match.
It seems to work in this Fiddle.
You can check the matches for the regex here.

var regex = /((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}/g;
var text = $("body:first").text();
text = text.replace(regex, "$&");
$("body:first").html(text);
please try this
demo: http://jsfiddle.net/PShYy/34/

Check this out: http://jsfiddle.net/PShYy/35/
// match every element in body, go to its contents
$("body:first").find('*').contents().filter(function(){
//if it's a text node, if its value matches the regex an it's not a child of an anchor
if(this.nodeType == 3 && regex.test(this.nodeValue) && this.parentElement.tagName !== "A"){
// create an anchor
var anchor = document.createElement('a');
// set its attribute to the phone number
anchor.setAttribute('href', this.nodeValue.match(regex)[0]);
// set the anchor's contents to be the same as its href attribute value
anchor.appendChild(document.createTextNode(this.nodeValue.match(regex)[0]));
// append it after the original text node
if(this.nextSibling)
this.parentElement.insertBefore(anchor, this.nextSibling);
else
this.parentElement.appendChild(anchor);
// remove the phone number from the original text node
this.nodeValue = this.nodeValue.replace(regex, '');
}
});
You could do it your way just by modifing the regex but if you replace the whole body with a new altered html, all the event listeners on your elements etc. will stop working.

Related

RegEx to only look at text inside HTML tags?

I recently started learning/using about RegEx.
Is there a way to avoid matching words that are HTML tag attributes or belonging to tag attributes?
For example:
<p style=“position: absolute”>position: </p>
I tried
/\bposition\b\W\s/g
But that matches both instances.
Can I only match the second “position: “?
Clarification:
I am trying to search the document for words that the user enters and replace them with a span element containing those words - this is similar to "Ctrl + F". Simply having the text is not enough as I would need a way to also update the document once the text was replaced with the span elements.
Disclaimer: Use stuff like document.innerText and other DOM APIs rather than Regex.
Match HTML tags:
<.+?>/g
Match everything within HTML tags (should handle nested ones as well):
/(?<=<.+.>)(.*?)(?=<.*\/.+.?>)/g
https://regex101.com/r/2uZHli/ for example of the above.
The RegEx to match the HTML / XML tags is /(<([^>]+)>)/ig. Maybe be this is what you're looking for.
let str = '<p style="position: absolute">position: </p>';
const strWithoutTag = str.replace(/(<([^>]+)>)/ig, '');
console.log(strWithoutTag);
You can try the Regex to match your temp, which matched the second "position: ".
/(?=\b.*(?<yourKeyword>position).*\b)(?<=<[^]*>)([^<>]+)(?=<\/([^<>]*)>)/g

JQuery : Delete span from title tag

Please how can I get a span into title tag i try to use
console.log($('title > span').text());
but it return an empty result. For example I want to get the word beautiful from this code :
<title>lorem epsum dolor <span class="spa">beautiful</span></title>
<title> tag should not include any-other tags inside it.
as stated here https://www.w3.org/TR/html401/struct/global.html#h-7.4.2
Titles may contain character entities (for accented characters, special characters, etc.), but may not contain other markup (including comments).
try this:
$('title span').html()
As Nate mentioned, a span tag is not valid within a title tag. However, if you still need to process it for whatever reason (for instance, a dynamically generated title from a database), you could use a regular expression.
<script>
var titleTag = $('title').text();
var match = titleTag.match(/<span>(.+)<\/span>/);
console.log(match[1]);
</script>

Replace HTML between two tags

What I want to do is replace what is in between two HTML tags.
I'm using this as a reference but I'm still encountering problems:
REFERENCE
This is what I've tried:
el.getValue().replace(/<form.+<\/form>/, "<div></div>");
I need to replace all my form tags dynamically.
If you use jQuery, just retrieve the parent element of what you'd like to be replaced, and replace the content with the .html() function.
Ex:
var formParentElement = $('#formParentElement');
formParentElement.html("<div>my new content</div>");
If you don't use jQuery:
var formParentElement = document.getElementById("formParentElement");
formParentElement.innerHTML = "<div>my new content</div>";
The example assumes the parent element of your form has an ID with value "formParentElement".
Yeah. I found a solution.
el.getValue().replace(/<form[\s\S]*?<\/form>/, "<div></div>");
Explanation by #[James G]:
[\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </form>.
Reference

Javascript : Replace Detect a string and replace html in a div after changing color

I am trying to change color of a part of strings. I have a list of DOM elements, and for each of them, the text can contain some hashtags. I would like to put in color all hashtags words which could be found in the text.
Here is the begin of the code :
var listOfText = document.getElementsByClassName("titleTweet");
for (var nodetext in listOfText) {
var divContent = listOfText[nodetext].innerHTML;
if (divContent.indexOf("#") !== -1) {
// Do job here
}
}
For example, divContent can be equals to "Hello my #friends ! How are you ?"
I would like to update the dom elements to put in red color the word "#friends".
I don't know how to do that using javascript or jQuery.
You can use a regexp to find the hastags and wrap them with html. Then use the .html() method to replace the original element's html with the new string.
Example snippet
$('#myDiv').replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
Working example - http://jsfiddle.net/4p4mA/1/
Edited the example to work on all divs on the page.
Note: This will only work so long as your element only contains text, because it is replacing all the child nodes with its text value.
use regex for this, find text having hashtag and replave that in span tag for each element.
$('.titleTweet').each(function(){
var $this=$(this);
$this.html($this.text()
.replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
});
See demo here
.innerHTML is a poor basis to starting replacing text. You'll want to navigate down to the text nodes and use .nodeValue to get the text. Then you can start splitting up the text nodes.

How to preserve whitespace in dynamically added javascript DOM element without using CSS?

When adding in text with small whitespace appended to it for alignment purposes the whitespace is trimmed off (the whitespace is added in c# so by the time it gets to front end Javascript it cannot be edited - it would be nice to just use some CSS to do this but it is not an option).
Here is what I tried so far:
var zlp = document.getElementById("testDiv")
zlp.innerHTML = "hello hello"
var zzz = document.createTextNode("hello hello")
zlp.appendChild(zzz)
<div id="testDiv"></div>
Both of which produce hello hello.
White space characters are usually collapsed in HTML (by default).
You can replace it with the entity:
var text = text.replace(/\s/g, ' ');
\s will match any white space character, such as space, tab and new line. If you only want to replace space, use / /g instead.
Other options which avoid string manipulation:
Put the text in a pre element.
Set the CSS 2 white-space property to pre as #Esailija pointed out. You can always add CSS properties dynamically to elements, they don't have to be specified in a style sheet.
use
zlp.innerHTML = "hello hello";
Like everyone else just said.
use a html tag 'pre'
Example:
<pre>
A line
A line with indent
</pre>
result:
A line
A line with indent
White space is collapsed in HTML. It's not a JS issue, the same would happen if you typed that manually in the HTML document. You need to replace the spaces with
zlp.innerHTML = "hello hello".replace( / /g, " " );

Categories

Resources