replace with some other text - javascript

I'm stuck in a thing where I need to replace with some other text.
I have tried the following code.
var text = $("#nbspData").text().replace(' ','a');
$("#removedData").html(text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="nbspData">this is me.</p>
<p id="removedData"></p>
But when I inspect the code the is not removed.

That happens because text() doesn't returns those encoded chars, it just returns the text you're seeing, e.g.: "this is me". So there is nothing to replace. Change text() to html():
var text = $("#nbspData").html().replace(' ','a');
var text = $("#nbspData").html().replace(' ','a');
$("#removedData").html(text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="nbspData">this is me.</p>
<p id="removedData"></p>
Additional info: Use a regex replace if you want to replace all occurences of :
var text = $("#nbspData").html().replace(/\ /g,'a');
console.log(text);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="nbspData">this is me.</p>

This is a solution for HTML tag and &nbsp etc and you can remove and add conditions
based on your reuirement
convertHtmlToText(passHtmlBlock)
{
str = str.toString();
return str.replace(/<[^>]*(>|$)| |‌|»|«|>/g, 'replaceWithAnyText');
}

Related

Use a checkbox to toggle between 2 numbers

How do I use a checkbox in JS/jQuery to toggle just between 2 numbers?
I want unchecked to always be $0 and checked to always be $100. The code below comes close. I'm looking to use str.replace as opposed to switching divs using display:none.
Code:
function myFunction() {
let str = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML = str.replace("$0", "$100");
}
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript String</h2>
<p>The replace() method searches a string for a specified value, or a regular expression,
and returns a new string where the specified values are replaced.</p>
<p id="demo">$0</p>
<input type="checkbox" onclick="myFunction()" value="Try It">
</body>
</html>
function myFunction() {
const element = document.getElementById('demo')
element.innerText = element.innerText === '$0' ? '$100' : '$0'
}

issue with using innerHTML() and inserting javascript variable values into HTML

I am working on a small word counter for a school assessment and can't see what is wrong with this code. The idea is when you hit the submit button, it displays "Word Count: " and the amount of character put into a text box. I have showed the teacher my code and he agrees that he doesn't see a problem with it.
Javascript:
window.onload = function(){
var input = document.getElementById(userInput).value;
if(submit.onclick) {
document.getElementById("wordCount").innerHTML = "Word Count: " + input.length;
};
};
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<h1 style='font-family:verdana;text-decoration:underline;'>Word Counter</h1>
<p>Please input text into the text box below:</p>
<input type='text' id='userInput'/>
<button id='submit'>Submit</button>
<p id='wordCount'></p>
<script type='text/javascript' src='script.js'></script>
</body>
</html>
document.querySelector('#submit').addEventListener('click', function(e) {
const input = document.querySelector('#userInput');
const inputValue = input.value;
const wordsArray = inputValue.split(' ');
document.querySelector('#wordCount').innerText = `Word Count: ${wordsArray.length}`;
})
<h1 style='font-family:verdana;text-decoration:underline;'>Word Counter</h1>
<p>Please input text into the text box below:</p>
<input type='text' id='userInput'/>
<button id='submit'>Submit</button>
<p id='wordCount'></p>
First on window load there is likely no information inside the #userInput, meaning
var input = document.getElementById(userInput).value; will be undefined or ''.
Second, you have no click event bound to your submit button so
submit.onclick will return false;
Binding DOM events
Lastly I switched from using .innerHTML to .innerText as there is no HTML being added into it. Also you your original code was not getting the word count, but would have returned the character count of the input text. To get word count I split the input text on spaces and returned the length of that array as the word count.
Try putting quotes around your userInput inside your getElementById. Right now you're trying to get an element by an ID of undefined because the userInput variable doesn't exist.

How to get Css Background image URL text from relative URL?

I want to get text of background-image URL.
Expect Output:
123
http://123.com
(It is empty)
But Actual Output:
$('#p1').html($('#bg1').css('background-image').replace('url(','').replace(')','').replace(/\"/gi, ""));
$('#p2').html($('#bg2').css('background-image').replace('url(','').replace(')','').replace(/\"/gi, ""));
$('#p3').html($('#bg3').css('background-image').replace('url(','').replace(')','').replace(/\"/gi, ""));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
I know that this function can be implemented by manipulating strings.
Is there any other way?
I know this css is not specification, But I want to write GreaseMonkey UserScript to hack other Website.
Solved:
This style.backgroundImage saved me! Thank!
$.fn.extend({
getBackgroundUrl: function () {
let imgUrls = [];
$(this).each(function (index, ele) {
let bgUrl = ele.style.backgroundImage || 'url("")';
bgUrl = bgUrl.match(/url\((['"])(.*?)\1\)/)[2];
imgUrls.push(bgUrl);
});
return imgUrls.length === 1 ? imgUrls[0] : imgUrls;
}
});
$('p').html($('a').getBackgroundUrl().join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p></p>
You can do that a lot easier with a single regular expression: match the url and the opening parentheses, capture the single or double quote, then capture and lazy-repeat characters until you get to the next single or double quote:
const getUrl = str => str.match(/url\((['"])(.*?)\1\)/)[2];
$('a').each((_, a) => console.log(getUrl(a.style.backgroundImage)));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
No need for a big library like jQuery just to select elements, you can do it in vanilla JS quite easily too:
const getUrl = str => str.match(/url\((['"])(.*?)\1\)/)[2];
document.querySelectorAll('a').forEach((a) => {
console.log(getUrl(a.style.backgroundImage));
});
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>

Why does replacement work in first line only

Why does the jquery replacment work in first line only?
var el = $('#X');
el.html(el.html().replace("&", "%26"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Line 1: <span id="X"></span>
Line 2: <span id="X"></span>
instead of html you use text() like below, it will work.
var el = $('#X');
el.html(el.text().replace("&", "%26"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="X">test & test1</span>
Its because the html string returned is encoded, and you need to decode it before replacing.

Adding text to an existing text element in JavaScript via DOM

I am trying to figure how to add text to a p tag or h1 tag that already has a text node.
For example:
var t = document.getElementById("p").textContent;
var y = document.createTextNode("This just got added");
t.appendChild(y);
<p id="p">This is some text</p>
This code gives an error appendChild is not a function. Most of the help pages first create a p tag and then append the text.
What is the right way to add text to an existing text element?
PS: I've used innerHTML before to do this, but for learning purposes I want to avoid it here.
The reason that appendChild is not a function is because you're executing it on the textContent of your p element.
You instead just need to select the paragraph itself, and then append your new text node to that:
var paragraph = document.getElementById("p");
var text = document.createTextNode("This just got added");
paragraph.appendChild(text);
<p id="p">This is some text</p>
However instead, if you like, you can just modify the text itself (rather than adding a new node):
var paragraph = document.getElementById("p");
paragraph.textContent += "This just got added";
<p id="p">This is some text</p>
Instead of appending element you can just do.
document.getElementById("p").textContent += " this has just been added";
document.getElementById("p").textContent += " this has just been added";
<p id ="p">This is some text</p>
The method .appendChild() is used to add a new element NOT add text to an existing element.
Example:
var p = document.createElement("p");
document.body.appendChild(p);
Reference: Mozilla Developer Network
The standard approach for this is using .innerHTML(). But if you want a alternate solution you could try using element.textContent.
Example:
document.getElementById("foo").textContent = "This is som text";
Reference: Mozilla Developer Network
How ever this is only supported in IE 9+
What about this.
var p = document.getElementById("p")
p.innerText = p.innerText+" And this is addon."
<p id ="p">This is some text</p>
remove .textContent from var t = document.getElementById("p").textContent;
var t = document.getElementById("p");
var y = document.createTextNode("This just got added");
t.appendChild(y);
<p id ="p">This is some text</p>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Appended text</b>.");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button id="btn1">Append text</button>
</body>
</html>
var t = document.getElementById("p").textContent;
var y = document.createTextNode("This just got added");
t.appendChild(y);
<p id="p">This is some text</p>

Categories

Resources