Replacing words with another word using javascript - javascript

I have the following code. I'm trying to change all instances of hello to hey. I have created a variable text to store the string. I have then tried the replace method on that string, but it does not change the string. I want the text in the <p> element tags to be changed to hey hey hey hey, but it does not change. What am I doing wrong?
HTML:
<p id="1">hello hello hello hello</p>
Javascript:
var text = document.getElementById("1").textContent;
text = text.replace(/hello/g,"hey");

You could do like this .
Why not working
For that initial call text= elem.textContent its read the value.
On the second time set text=replace value is not possible .Because the text only have string p elem not a DOM elem
var text = document.getElementById("1").textContent;
console.log(text) //direct string
text = text.replace(/hello/g, "hey")
<p id="1">hello hello hello hello</p>
Solution
var text = document.getElementById("1");
console.log(text) //dom element
text.textContent = text.textContent.replace(/hello/g, "hey")
<p id="1">hello hello hello hello</p>

Related

Replacing text in an input box of a webpage

I wanted to replace a particular text "Dog" in an input box of a webpage to the text "Cat". I am new to jaavascript, so please pardon me for asking this question if I happen to break any forum rules.
Thank you in advance. Vicky.
You can get an element by it's id and then change it's value
document.getElementById("nameofid").value = "Cat";
you can use replace() function fot that.
const ta = document.querySelector("textarea");
const str = ta.value.replace("dog","cat");
ta.value = str
console.log(ta.value,"change to" ,str)
<textarea>a little dog.</textarea>
<html>
<body>
<h2>Change input box to Cat</h2>
<div id="inputBoxId">Dog</div>
<script>
document.getElementById("inputBoxId").innerHTML = "Cat";
</script>
</body>
</html>

Why isn't "innerHTML" working when I try to insert onclick events on all the items of an array using the "forEach" method?

I am trying to get a text and add an onclick event with a function on each word of the text. It works perfectly with some sentences, but it doesn't with others. When it doesn't work, part of the html tags are displayed on the page. I noticed that it never works when there are repeated words or when I use the words "a" or "an", but I don't know why.
Here is how I am doing it:
I enter the text in the page using a textarea tag.
<textarea id="text-input"></textarea>
Then I grab the text, split it into an array with all the words and add an onclick event with a function to each word.
function addLink(){
let text = document.getElementById('text-input').value
const words = text.match(/\w+/g)
words.forEach(word => {
text = text.replace(word, `<span onclick=showWordDetail('${word}')>${word}</span>`)
})
document.getElementById('result').innerHTML = text
}
function showWordDetail(word){
let wordDetail = document.getElementById('word-detail')
result = `<h3>${word}</h3>`
return wordDetail.innerHTML = result
}
The "addLink" function is called when I submit the text.
<button onclick="addLink()">Submit</button>
If I enter, for example, "My brother is engineer". It works perfectly. The onclick event is added to all the words.
But if I enter "My brother is an engineer", this is the result:
"an onclick=showWordDetail('My')>My brother is an engineer."
I console.log'ed the array of all my attempts and the text is split correctly. So I have no idea why sometimes it works, but sometimes it doesn't.
I think this is what you want. It avoids some of the problems of the answers that just split at spaces.
const wordDetail = document.getElementById('word-detail'),
input = document.getElementById('text-input'),
result = document.getElementById('result');
function addLink() {
result.innerHTML = input.value.replace(/\w+/g,`<span onclick="showWordDetail('$&')">$&</span>`)
}
function showWordDetail(word) {
wordDetail.innerHTML = `<h3>${word}</h3>`
}
<textarea id="text-input"></textarea>
<button onclick="addLink()">Submit</button>
<div id="result"></div>
<hr/>
<div id="word-detail"></div>
My brother is an engineer
So this includes the word an.
Now look at what you replaced My with:
<span onclick=showWordDetail('My')>My</span>
So when you get to an what is going to be replaced?
What is the first place that the sequence of characters an attpears?
The an of the <span>
You would probably be better off with something like:
const html = words.map(word => `<span ....>${word}</span>`).join(" ");
document.getElementById('result').innerHTML = html
where you build a new set of HTML piece by piece instead of trying to replace the old content piece by piece.
Use split() instead, with separator space and replace every word, after replace it, add it to text value like that:
function addLink(){
let text = document.getElementById('text-input').value;
const words = text.split(" ");
text = "";
words.forEach(word => {
text += word.replace(word, `<span onclick=showWordDetail('${word}')>${word}</span> `);
});
document.getElementById('result').innerHTML = text;
}
function showWordDetail(word){
let wordDetail = document.getElementById('word-detail');
wordDetail.innerHTML = `<h3>${word}</h3>`;
}
<textarea id="text-input"></textarea>
<button onclick="addLink()">Submit</button>
<p id="result"></p>
<div id="word-detail"></div>

Is it possible to put another div or HTML element replacing "Hello World" text?

<body onload="myfunction('target')"><div id="target"> "Hello World" </div></body>
Is It Possible To Put Another Div Or HTML Element Replacing "Hello World" Text?
Hello World is a Left To Right Marquee Text
<script language="javascript">
function myfunction(id) {
var element = document.getElementById(id);
var textnode = element.childNodes[0];
var text = textnode.data;
setInterval(function() {
text = text[text.length - 1] + text.substring(0, text.length - 1);
textnode.data = text;
}, 400)
}
</script>
If you're just trying to replace the text that is in the innerHTML/innerText querying the HTML element and simply setting it's innerHTML/innerText to the new value will suffice.
Example:
const myElement = document.getElementByTagName('h1')
myElement[0].innerHTML = 'new value'
if you want to change html inside div and change to another div or text or any html
you can do like this you don't need to replace
$('#target').html('<div class="col-md-2"></div>');
and if you want to replace then you can do like this
$('#target').html().replace("hello",'<div class="col-md-2"></div>');
innerHTML should do the trick, if you are trying to add html elements:
Here is the working example of your code snippet:
https://codebrace.com/editor/b15cd15b3
Example:
...
element.innerHTML = "<span style='color: red; background-color:yellow;'>" + text + "</span>";
...
html code
<body onload="myfunction()">
<div id="target"> Hello World </div>
</body>
javascript code
function myFunction() {
var str = document.getElementById("target").innerHTML;
var res = str.replace("Hello World", "testing");
document.getElementById("target").innerHTML = res;
}
myFunction();
Replacing the helloworld html to testing html using onload function.

Html - insert html into <p> </p> tags

Let's say I have a text :
<p> hello world! </p>
and I am using a function that cut the text after 5 words and adds " ...show more"
I want the result to be like this :
hello ... show more
Because of the <p> tags what I get is this output :
hello ...show more
what I see when I inspect the element is this :
<p> hello </p> ...show more
I must mention that the text can be with <p> or without.
Is there a way to solve this problem ?
Is there a way to insert the added text inside the <p> tag ?
I need to mention that I need the <p> tags, I can't use strip tags function.
Thanks,
Yami
Do you mean this?
var text = "<p>hello world</p>";
var res = "<p>" + text.substring(3, 8) + " ...show more</p>";
It results in:
<p>hello ...show more</p>
The way I see it, you have two options:
.split() the string by spaces (assuming a space separates words) then slice the first (up to) 5 elements. If there are greater than 5 element, add "...read more"; if not, it's unnecessary.
You can use some regex replace and (with a negative lookahead) ignore the first 5 words, but replace all other text with your "...read more". (I personally find this one having more overhead, but you could probably use (?!(?:[^\b]+?[\b\s]+?){5})(.*)$ as a pattern)
Having said that, here's what i mean with a string split:
function readMore(el){
var ary = el.innerHTML.split(' ');
el.innerHTML = (ary.length > 5 ? ary.slice(0,5).join(' ') + '... read more' : ary.join(' '));
}
var p = document.getElementById('foo');
readMore(p);
Assuming of course, for the purposes of this demo, <p id="foo">Hello, world! How are you today?</p> (which would result in <p id="foo">Hello, world! How are you...read more</p>)
$('p').text($('p').text().replace('world!', '... show more'));

selecting text between round brackets in javascript

I need to select a text using javascript that is between round brackets, and wrap it all in a span:
<p>Just some text (with some text between brackets) and some more text</p>
should become:
<p>Just some text <span class="some-class">(with some text between brackets)</span> and some more text</p>
I think something like this should be possible using regex, but i'm totally unfamiliar with using regex in javascript. Can someone please help? Thanks!
This should do the trick (str is the string holding the text you want to manipulate):
str.replace((\([^()<>]*\)), "<span class=\"some-class\">$1</span>");
It disallows (, ), < or > within the parenthesis. This avoids nesting issues and html tags falling in the middle of the parenthesis. You might need to adapt it to meet your exact requirements.
Since you're new to regular expressions, I recommend reading http://www.regular-expressions.info/ if you want to learn more.
oldString = '<p>Just some text (with some text between brackets) and some more text</p>';
newString = oldString.replace(/\((.*?)\)/g, '<span class="some-class">($1)</span>');
Try this:
<p id="para">Just some text (with some text between brackets) and some more text</p>
<input type="button" value="Change Text" onclick="ChangeText()"/>
<script>
function ChangeText()
{
var para = document.getElementById("para");
var text = para.innerHTML;
para.innerHTML = text.replace(/(.*)(\(.*\))(.*)/g, "$1<span class=\"some-class\">$2</span>$3")
}
</script>
Using RegExp object:
var str = "<p>Just some text (with some text between brackets) and some more text</p>";
var re = new RegExp("\(+(.*)\)+", "g");
var myArray = str.replace(re,"<span class="some-class">($1)</span>" );
Using literal:
var myArray = str.replace(/\(+(.*)\)+/g,"<span class="some-class">($1)</span>")

Categories