Replace the contents of a div with regex match of string - javascript

I'm trying to figure out how to replace the contents of a <div> with the results from a regex .match() statement on a string. This is the code I have so far but I can't get it to work. I want the button to stay on screen but the <div> to reflect the matched word.
<html>
<body>
<script type="text/javascript">
function search(){
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.write(str.replace(document.getElementById("results"),
(str.match(patt1))));
}
</script>
</body>
<div id="results">So this is some text.</div>
<button name="Search" onclick="search()">Click Here</button>
</html>
Any ideas as to why it's not working?

You need to stop the button completing it's default event, which is to submit the page. (Edit: No it's not, its default event is nothing - assumed it was a <submit> :) )
In addition, to get a div from the document basic on it's id attribute, you use document.getElementById('id-of-element') and to set the contents of a div, you use .innerHTML on the element we just got.
// We need to take the event handler as a parameter for the function, let's call it e
function search(e){
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.getElementById("results").innerHTML = str.match(patt1)[0];
// This line stops the default action occurring
e.preventDefault();
}
Note: we don't need to specify an argument here, e goes in automatically
<button name="Search" onclick="search()">Click Here</button>

Your code is searching for the String "So this is come text." in the String "Visit W3Schools" and replacing it with the array ["W3Schools"], then writing it to the screen. This doesn't make much sense.
Try something like this instead:
function search(){
var str = "Visit W3Schools";
var patt1=/w3schools/i;
document.getElementById("results").innerHTML=(str.match(patt1))[0];
}

document.write will replace the entire page with the passed in parameter. So you just want to update that single DIV, results. So you want to use innerHTML:
function search() {
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.getElementById("results").innerHTML = str.match(patt1)[0];
}

Related

txt.replace </blockquote> in textarea js

I give up! I looked at many different answers. I've tried many different ways and nothing works. I want to change the </blackquote> tag to <br /> or a new line in the textarea. Alternatively, change to some other character, because later I can replace another character in PHP to <br/>. How to do it?
Working example for easy understand here: https://jsfiddle.net/jsf88/rb3xp7am/35/
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎 </blockquote><br />
"X" -- HERE I want BR_TAG or new line in textarea after click 'quote' 😐
</div>
</section>
$(document).on('ready', function() {
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').text();
//txt = txt.replace('</blockquote>', '<br/>');
//txt = txt.replace(/<\/(blockquote)\>/g, "<br/>");
//txt = txt.replace(/blockquote*/g, '<br/>');
//txt = txt.replace(/(.*?)<\/blockquote>(.*?)/g, ' xxx ');
txt = txt.replace(/<\/blockquote>/gi, '<br/>')//NOT WORKING!!
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');//working great
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]'));
});
});
To make it funnier, another example with changing the blackquote tag to br works without a problem. Why? can someone explain it?
//OTHER EXAMPLES WHERE CHANGE </BLACKQUOTE> to <br/> WORKING GOOD... WTF?!
string = ` <blockquote>this is a quote for comment😎 </blockquote><br />"X" -- HERE I want BR_TAG or new line in textarea after click 'quote' 😐`;
string = string
.replace(/<\/blockquote>/gi, ' <br /> ');//but here working! ;/
console.log(string);
you recover text with text function ('.replyMsg').text() but in that case you will have the text but with no html tag like <blockquote> so first you will have to recover the html to have the blockquote tag
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
the br tag is not interpreted in textarea so you have to change it by a new line character
don't forget to remove opened bloquote tag to get the expected result
txt = txt.replace(/<blockquote>/gi, '');
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');
txt = txt.replace(/<\/blockquote>/gi, '\n');
txt = txt.replace(/<blockquote>/gi, '');
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]'));
});
blockquote {
background-color: silver;
}
.replyMsg {
border: 2px solid green;
}
.quoteMsg {
background-color: green;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎 </blockquote>
"X" -- HERE I want BR_TAG or new line in textare a after c lick 'quote' 😐
</div>
</section>
The first problem in your code was how you were adding the event listener to the ready event. Being it something invented by jQuery, and not a native event, the correct way to do it should be as of now (v.3.3.1 the version I used in this demo) $(document).ready(()=>{/*code here*/}).
As a further reference:
https://api.jquery.com/ready/
There is also $(document).on( "ready", handler ), deprecated as of
jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes
ready before this event is attached, the handler will not be executed.
But... it's not perfectly clear how did you wish to transform your text before setting the value of the textarea. So I just better factored your logic so that you have some clear steps:
grabbing the blockquote element text content and trimming it (being the origin)
applying the transform newline to whitespace (with the regex that I left untouched)
build the final string as a template literal that will include the quote content, the meta tags wrapping it, AND anything else you wish to add like for example a new line (\n) that in this example is exacerbated by a text following it.
There's a hint in your words that put me in the position to say something superflous but still deserving an attempt: the value of a inner text is just plain text and doesn't render html content. So the <br> itself would remain as you read it and wouldn't have any rendering effect on the textarea content. That's why I focused my demonstration on putting a newline with the escaping sequence. It works both on double quoted strings and template literals: "\n" `\n`
Further notes
It seems the original approach of processing the blockquote html was preferred. It's worth saying that it was appearently a terrible strategy for several reasons:
It grabs the blockquote content as html despite that's not how it's
rendered on the page.
It takes the effort to consider the whole outerHTML removing the
wrapping blockquote tags instead of fetching directly the innerHTML.
It adds the newline as newline instead of embedding it as <br> so
at this point I ask myself if the content in the textarea was
supposed to be encoded html or not.. and the added br would then
belong to something meta?
It's harder to deal with in case you want to further customize the
string processing
But... maybe there's something I didn't get and I'm doing weak assumptions.
//since you are using the ready event with jquery, that's the correct syntax
$(document).ready(function() {
$('.quoteMsg').click(function() {
//grabs the text content of the blockquote element (trimming it)
var quoteTextContent = $(this).closest('.replyBox').find('.replyMsg').text().trim();
//performs the transform already in place in your code.. replacing newlines with white spaces
quoteTextContent = quoteTextContent.replace(/(?:\r\n|\r|\n)/g, ' '); //working great
//builds the string to set the textarea value with, using a template literal
//here you can add anything you want.. like a new line but that's just an example
const encoded = `[quote]${quoteTextContent}[/quote]\nand something following to show the new line happening`;
console.log(encoded);
$("textarea[name='quote']").val( encoded );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="comment" name="quote" placeholder="quote" style="width:80%;height:200px;"></textarea>
<section class="replyBox" style="width: 100%;"><br/>
[ click for quote ]
<div class="replyMsg">
<blockquote>this is a quote for comment😎
<br>
Having new lines also ... since you perform a regex transform newline=>whitespace
</blockquote><br />
</div>
</section>
Well, thanks for answers. The problem was a missing .html tag.
This script work for me almost perfect for quoting few times:
$(document).on('ready', function() {
$('.quoteMsg').click(function() {
var txt = $(this).closest('.replyBox').find('.replyMsg').html();
txt = txt.replace(/(?:\r\n|\r|\n)/g, ' ');
txt = txt.replace(/</g, "<");
txt = txt.replace(/>/g, ">");
txt = txt.replace(/&/g, "&");
txt = txt.replace(/"/g, '"');
txt = txt.replace(/'/g, "'");
txt = txt.replace(/<br>/g, "");
txt = txt.replace(/<hr>/g, "[hr]");
//txt = txt.replace(/<hr>/g, "\n");
txt = txt.replace(/<blockquote>/gi, '');
txt = txt.replace(/<\/blockquote>/gi, '[hr]');
txt = txt.replace(/[hr][hr]/gi, "");//not working ([][])
txt = txt.replace(/[hr][hr]/gi, "[hr]");//not working ([[hr]][[hr]])
console.log(txt);
$("textarea[name='quote']").val($.trim('[quote]' + txt + '[/quote]\n'));
});
});
The problem here is I dont know how to change dubble [hr][hr] for nothing, because this txt = txt.replace(/[hr][hr]/g, ""); not working, so would be cool for more explain about. One more time big thanks for answers! this function .replace is not as intuitive as in PHP.
EDIT: ahh.. I think is not possible to delete this dubel, because I extra insert it two times. Nvm. I will find and del this dubel in PHP.

Regex number filtering from textarea

I have been looking for way how I could filter data within textarea using regex function for a quite a while now without any success. Below is the regex I want to use to filter UK telephone numbers.
(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?
Fiddle: https://jsfiddle.net/qdypo04y/
I want to achieve the result when the button is clicked it will remove lines which do not meet the regex? Alternatively would remove values which are not UK telephone numbers.
Any guidance would be appreciated.
Apart the use of textarea element your issue is:
how attach click event listener to your button (refer to: querySelector and addEventListener)
how get the content of textarea and split it into rows (refer to: textContent plus split and join)
finally how use your regex: refer to test
An example is:
document.querySelector('button').addEventListener('click', function(e) {
var txtArea = document.querySelector('textarea[rows="4"][cols="50"]');
var re = /(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?/;
var txtArr = txtArea.textContent.split('\n');
txtArr.forEach(function(ele, idx) {
txtArr[idx] = ele + ' test result is: ' + re.test(ele);
});
txtArea.textContent = txtArr.join('\n');
});
<textarea rows="4" cols="50">
+447222555555
0800 042 0213
2017/07/14
2017/07/17
2017/07/27
</textarea>
<button>Click me</button>
<script>
function myFunction() {
var regexp = /(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?/;
var content=$.trim($("textarea").val()).split('\n');
var result="";
for(var i = 0;i < content.length;i++){
if(regexp.test(content[i])){
result=result+content[i]+'\n';
}
}
$("textarea").val(result);
}
</script>
used JQuery to take the value from textarea

How can i get my string replace with to equal the value of a form input?

Im trying to use string replace to change a line of code within my page.
<script type="text/javascript">
function replaceScript() {
var toReplace = 'LINE OF CODE 333';
var replaceWith ='??????????';
document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith);
}
</script>
How can I get my...
var replaceWith ='??????????';
...to equal the value of an input from a form on the page?
Note the input value is auto populated on page load and the user does not enter in there own email address.
I assume you have an input such as <input id="inputValue" type="text" />
The general approach is to use a DOM function like getElementById() or querySelector(), and access its value with the value property.
Your code could be as simple as:
<script type="text/javascript">
function replaceScript() {
var toReplace = 'LINE OF CODE 333';
var replaceWith = document.getElementById('inputValue').value;
document.body.innerHTML = document.body.innerHTML.replace(toReplace, replaceWith);
}
</script>

Javascript: help with replacing '<div>' with '<br>' of an innerHTML!

I have an editable div where the user writes. As he writes, a javascript function adds the div html to a textarea. When the user presses SHIFT+Enter, the div gets a <br>. This is good.
But when the user presses Enter alone, the div gets <div></div> tags.
Therefore I try to make it so that when Enter is pressed, javascript scans the div's html to eliminate the </div> and change the <div> for <br>. The result will be that regardless of whether the user presses SHIF+Enter or Enter, the div's html will end up using only <br> for linebreaks.
<head>
<script type="text/javascript">
function doStuff(e){
if (window.event.keyCode == 13) {
var s=document.getElementById("divv").innerHTML;
s.replace("<div>", "<br>");
s.replace("</div>", "");
document.getElementById("divv").innerHTML=s;
}
document.getElementById("txtt").value = document.getElementById("divv").innerHTML;
}
</script>
</head>
<body>
<div contenteditable="true" id="divv" onKeyUp=doStuff(event);">
write here! Then press enter!
</div>
<textarea id="txtt" rows="30" cols="100">
</textarea>
</body>
My code doesn't work. When Enter is pressed, The textArea still shows div tags.
I'm not sure what I'm doing wrong. Please help.
The replace() method does not modify the string it's called on, it returns a new string with the occurrences replaced.
You can do something like:
var divv = document.getElementById("divv");
divv.innerHTML = divv.innerHTML.replace("<div>", "<br>").replace("</div>", "");
Usually browsers will have innerHTML store tags as <DIV> and </DIV> - you could try using:
s = s.replace(/<div>/ig,"<br>");
s = s.replace(/<\/div>/ig,"");
Firstly, if you use xhtml, you must use tag "< br / >".
Also draw attention on str.replace: it replaces only once.
js> var x = "hello";
js> x.replace("l", "L");
heLlo
Make your replace implementation:
js> function myreplace(str, pattern, change_to) {
var s = str;
var s2 = s;
do {
s2 = s;
s = s.replace(pattern, change_to);
} while (s2 != s);
return s;
}
js> myreplace("helllllo", "l", "L");
heLLLLLo

javascript string.lastIndexOf does not work with span innerHTML

look the below example.
<html>
<body>
<form>
<span id="spTest">Your current operation: Modify » newone</span>
</form>
<script type="text/javascript">
var sp = document.getElementById("spTest");
var str = sp.innerHTML;
//var str = "Your current operation: Modify » newone";
alert(str)
var index = str.lastIndexOf("»");
alert(index);
</script>
</body>
</html>
the above example will popup the "index" value -1. If I uncomment the line ""Your current operation: Modify » newone";", the result will be 30.
So I think the reason is because I use the "innerHTML" to get the text. What else can i use the get text inside span and get the right index result?
Thanks
No, it has nothing to do with innerHTML. In the call to lastIndexOf, the » entity is not expanded as it is in the HTML code; instead it is considered as a raw string. Replace it with the actual character and it will work:
var index = str.lastIndexOf("»");
If you use innerHTML, you have to use "»" instead of "»".

Categories

Resources