It is working fine for first occurrence but i have multiple matched URL occurrence is not replacing.
If i am using global tag 'g' first occurrence also not working.
I need to change all the matched URL.
HTML:
<p id="demo">
Welcome to US and s sdfsdfsdf sdfsdfUS dfsdfsdfsdUS sfsdfsdfsdfsdfUS
</p>
JS:
var str = document.getElementById("demo").innerHTML;
var res = str.replace("http://google.com?sdfsdf", "sample link url");
document.getElementById("demo").innerHTML = res;
We can use the jQuery attribute contains selector to select all links that contain the href value you're looking for
var searchString = 'http://google.com?sdfsdf'; // specify the search value
var replaceString = 'Replace with me'; // specify the value to replace found strings with
// for each anchor tag with an href containing the search string
$("a[href*='" + searchString + "']").each(function(){
// replace its current href with a the search string replaced
$(this).attr('href', $(this).attr('href').replace(searchString, replaceString));
});
NB: If you are actually attempting to replace the entire url of the matched elements, you can eliminate the need for the .replace function, like so:
$(this).attr('href', replaceString);
check this. this might work https://jsfiddle.net/sfhmvrdo/
google
more google
fb
<button>
click here
</button>
this is the jquery you need.
$('button').click(function(){
change_href();
});
function change_href(){
$("a").each(function() {
if($(this).attr('href')=="http://google.com"){
$(this).attr('href','http://facebook.com');
}
});
}
Related
I am trying get all HTML links in a website's body section within a string and replace them to another link.
Tried something like this but did not work:
var search = "https://www.cloudflare.com/5xx-error-landing?utm_source=error_footer";
var replacement = "https://example.com/";
document.body.innerHTML = document.body.innerHTML.split(search).join(replacement)
Where "https://www.cloudflare.com/5xx-error-landing?utm_source=error_footer" is the link I want to replace and "https://example.com/" is the link that I want to replace with.
How about this:
$("[href='your link']").attr("href","new link");
Here is a solution with plain javascript as per your question
document.querySelectorAll("[href='" + search + "']").forEach(function(el){
el.href = replacement );
});
If you want to use jQuery, as you tagged, follow the answer of Nir Tzezana
$('body').find('a').each(function(){
$(this).attr('href','your_new_link');
});
or for different href:
$('body').find('a').each(function(){
var ahref = $(this).attr('href');
if ( ahref == 'your_old_link') { /// or ahref.indexOf("your_old_link") >= 0
$(this).attr('href','your_new_link_1');
}else{
$(this).attr('href','your_new_link_2');
}
});
Just use
$("body a[href='https://www.cloudflare.com']").attr("href","https://example.com/");
I have a div tag with contenteditable set to true.
I am trying to find out the last entered word in the div.
For example, if I type in This is a test and I hit a space, I want to be able to get the word test
I want to be able to use this logic so that I can test each word being typed (after the space is pressed).
It would be great if someone could help me with this.
An easy solution would be the following
var str = "This is a test "; // Content of the div
var lastWord = str.substr(str.trim().lastIndexOf(" ")+1);
trim might need a shim for older browsers. (.replace(/\s$/,""))
To strip punctuation like " Test!!! " you could additionally do a replace like following:
lastWord.replace(/[\W]/g,"");
You might want to do a more specific definition of the characters to omit than \W, depending on your needs.
If you want to trigger your eventhandler also on punctuation characters and not only on space, the last replace is not needed.
You first have to know when the content is edited. Using jQuery, that can be done with
$("div").on("keyup", function(){ /* code */ });
Then, you'll have to get the whole text and split it into words
var words = $(this).text().trim().split(' ');
And getting the last word is as complicated as getting the last element of the words array.
Here's the whole code
HTML
<div contenteditable="true">Add text here</div>
JavaScript (using jQuery)
$("div").on("keyup", function(){
var words = $(this).text().trim().split(' '),
lastWord = words[words.length - 1];
console.log(lastWord);
});
Demo
This is the ultimate way:
// listen to changes (do it any way you want...)
document.querySelectorAll('div')[0].addEventListener('input', function(e) {
console.log( getLastWord(this.textContent) );
}, false);
function getLastWord(str){
// strip punctuations
str = str.replace(/[\.,-\/#!$%\^&\*;:{}=\_`~()]/g,' ');
// get the last word
return str.trim().split(' ').reverse()[0];
}
DEMO PAGE
You can try this to get last word from a editable div.
HTML
<div id='edit' contenteditable='true' onkeypress="getLastWord(event,this)">
</div>
JS
function getLastWord(event,element){
var keyPressed = event.which;
if(keyPressed == 32){ //Hits Space
var val = element.innerText.trim();
val = val.replace(/(\r\n|\n|\r)/gm," ");
var idx = val.lastIndexOf(' ');
var lastWord = val.substring(idx+1);
console.log("Last Word " + lastWord);
}
}
Try this link http://jsfiddle.net/vV2mN/18/
Using javascript I'm looping through my H3 elements like this:
$('h3').each(function(){ });
I'm then generating an anchor for that tag formatted like this: "section-x" where x increments for each H3 on the page. The problem I have is that I'd like the first letter of the header to be an anchor link, like this:
*H*eading
.. where H is underlined, representing a link. I can format the anchors however I don't know how to wrap a hyperlink tag around the first letter in each heading. Some help would be greatly appreciated.
Regards,
kvanberendonck
Something like this?
$('h3').each(function(){
var currentHeading = $(this).text();
$(this).html("<a href='link'>" + currentHeading.substr(0,1) + "</a>" + currentHeading.substr(1, currentHeading.length - 1));
});
Let's throw some plain javascript into the mix:
$('h3').html(function(i){
var self = $(this)
, html = self.html()
return html[0].anchor('section-'+i) + html.substring(1)
})
html (and most other setter functions) accepts a function as an argument and uses the return value for each element
"string".link(target) creates the code string. A nice vintage useful method
edit: switched from .link to .anchor. Anchors are deprecated though, you should start using IDs for that:
$('h3').html(function(i){
var self = $(this)
, text = self.text()
// give the H3 an id and link to it
// ideally the headers should already have an id
this.id = 'section-'+i
return text[0].link('#section-'+i) + text.substring(1)
})
$('h3').each(function(i){
var firstLetter = $(this).text()[0];
$(this).html('' + firstLetter + '' + $(this).text().substr(1));
});
Not sure where you'd like to put section-x in that heading, but you can use i inside that each() to get the current iteration index.
The tricky part is not selecting the elements here, but just selecting the text within. The only true jQuery that will give you back text contents is .contents(). So I'm getting the contents of every element not he page, and I want to pick out a word, such as "hashtag". Then append to it.
What am I doing wrong here:
<html>
<p>
The word hashtag is in this sentence.
</p>
</html>
jQuery:
$(function() {
$('*')
.contents()
.filter(function(){
return this.nodeType === 3;
})
.filter(function(){
return this.nodeValue.indexOf('hashtag') != -1;
})
.each(function(){
alert("It works!")
});
});
$('*') grabs every element
.contents() grabs the contents of every element
.filter(function(){ return this.noteType === 3; refines it down to the text contents of elements. (#3 node type is text)
return this.nodeValue.indexOf('hashtag') should grab the word "hashtag". Not sure if this is working.
!= -1; should prevent it from grabbing every single element in the HTML. Not sure about that one.
Why doesn't it work? I know I have anything appending tags yet, but can I select the word "hashtag" thanks!
If you want to do this for the whole page you can work on the HTML of the body element:
$(function() {
var regExp = new RegExp("\\b(" + "hashtag" + ")\\b", "gm");
var html = $('body').html();
$('body').html(html.replace(regExp, "<a href='#'>$1</a>"));
});
Keep in mind that this may be slow if your page is large. Also, all elements will be rewritten and thus loose their event handlers etc.
If you don't want this or want to restrict the replacement to certain elements, you can select and iterate over them:
$(function() {
var regExp = new RegExp("\\b(" + "hashtag" + ")\\b", "gm");
$('div, p, span').each(function() { // use your selector of choice here
var html = $(this).html();
$(this).html(html.replace(regExp, "<a href='#'>$1</a>"));
});
});
JS :
function replaceText() {
$("*").each(function() {
if($(this).children().length==0) {
$(this).html($(this).text().replace('hashtag', '<span style="color: red;">hashtag</span>'));
}
});
}
$(document).ready(replaceText);
$("html").ajaxStop(replaceText);
HTML :
<html>
<p>
The word hashtag is in this sentence.
</p>
</html>
Fiddle : http://jsfiddle.net/zCxsY/
Source : jQuery - Find and replace text, after body was loaded
This is done with span but will work with obviously
The clean variant would be this:
$(function() {
var searchTerm = 'hashtag';
$('body *').contents()
.filter(function () {
return this.nodeType == 3
&& this.nodeValue.indexOf(searchTerm) > -1;
})
.replaceWith(function () {
var i, l, $dummy = $("<span>"),
parts = this.nodeValue.split(searchTerm);
for (i=0, l=parts.length; i<l; i++) {
$dummy.append(document.createTextNode(parts[i]));
if (i < l - 1) {
$dummy.append( $("<a>", {href: "", text: searchTerm}) );
}
}
return $dummy.contents();
})
});
It splits the value of the text node at searchTerm and re-joins the parts as a sequence of either new text nodes or <a> elements. The nodes created this way replace the respective text node.
This way all text values keep their original meaning, which cannot be guaranteed when you call replace() on them and feed them to .html() (think of text that contains HTML special characters).
See jsFiddle: http://jsfiddle.net/Tomalak/rGcxw/
I don't know jQuery very much but I think you can't just say .indexOf('hashtag'), you have to iterate through the text itself. Let's say with substring. Probably there's an jQuery function that will do this for you, but that might be your problem for finding 'hashtag'.
Let's say the window's location is on htt://stackoverflow.com/index.php, I want to remove an element in the index page with jQuery. This is what I have and it's not working:
$(document).ready(function() {
var location = window.location;
var locQuery = /index/i;
if (location.match(locQuery)) {
$('.someClass').removeClass();
}
});
You are only removing it's class, so for example
<div class="someclass"></div>
will change into
<div></div>.
try
$('.someClass').remove();
I found the problem. window.location is an object so the .match method couldn't match anything from the regex. I had to use the .href property of window.location to get a match.
var location = window.location.href;
var locQuery = /index/i;
if (location.match(locQuery)) {
$('.someClass').remove();
}
I hope I use the right terms. I'm new to JavaScript.