Javascript replace every line of value - javascript

So I have this script which has to find some text on the first textarea (right away when text is pasted), then replace it with another one and give the result to another textarea.
The problem is that it's replacing the text only for the first line. And I want it to replace it on the All lines.
My code: (doesn't work on JSfiddle, but do on HTML)
<script>
function go()
{
var str = document.getElementById("a").value;
resa=str.replace("http://","www.");
resb=resa.replace(".com","");
document.getElementById("b").value=resb;
}
</script>
<textarea rows="10" cols="140" onkeyup="go()" id="a">
</textarea>
<textarea rows="10" cols="140" onkeyup="go()" onclick="this.focus();this.select();" id="b">
</textarea>
So if you try to enter https://google.com in every line you will get right text on the other textarea, but only in the first line.

You need to do a global replace.
var str = document.getElementById("a").value;
var resa=str.replace(/http\:\/\//g,"www.");
var resb=resa.replace(/\.com/g,"");

It's not that only the first line is replaced. The problem is you're only replacing the first occurrence.
Change to use a regex to replace all:
var resa = str.replace(new RegExp('http://', 'g'), 'www.');
var resb = resa.replace(new RegExp('.com', 'g'), '');
document.getElementById("b").value = resb;

Related

Preserve line breaks while substituting anything except the first letter and punctuation marks

jQuery("#memorize-form").submit(function(){
var text = jQuery("#n-text").val();
var substitute_with = "_";
const regex = /\B\w/g;
var result = text.replaceAll(regex, substitute_with);
jQuery("#result").html(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="memorize-form" action="" method="get">
<textarea id="n-text" rows="10"></textarea>
<button id="memorize-submit">Convert</button>
</form>
<span>Result: </span><span id="result"></span>
This code replaces all the letters except the first on with the underscore. The punctuation should be made intact.
The text is input by the user.
The problem with it is that the text contains a line break, the line break is not preserved. It should be preserved.
Try this:
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.
The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.
P.S.: The result disappears from the screen. Why is this?
Very simple, just detect \n and replace it with <br/>
jQuery("#memorize-form").submit(function(e){
e.preventDefault(); //prevents form submit
e.stopImmediatePropagation(); //prevents form submit
var text = jQuery("#n-text").val();
var substitute_with = "_";
const regex = /\B\w/g;
var result = text.replaceAll(regex, substitute_with);
//recommended way
if(result.match(/[^\r\n]+/g)){ //check for \n and replace it with <br>
result = result.replaceAll('\n','<br/>');
//result = result.replace('\r','<br/>'); handle \r if needed
}else{
//not recommended way
//check for . `fullstops` and add a br.
//if(result.includes('.')){
// result = result.replace('.','<br/>');
//}
}
jQuery("#result").html(result);
});
Tested code!

Converting \n to <br/>

I'm having problem converting \n to a < br / >
function format() {
var text = document.getElementById("formatArea").value;
text.replace("\n", "<br/>");
document.getElementById("resultArea").value = text;
}
<textarea rows="20" cols="80" id="formatArea">
</textarea>
<textarea rows="20" cols="80" id="resultArea">
</textarea>
<button onclick="format()">Click to create HTML breaks</button>
Appreciate any help, i'm not very experienced in JS yet.
You have 2 issues here.
Firstly, replace does not change the original string, it returns a modified string. (Documentation link : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
Secondly, if you put a string in the first parameter of replace, it will only replace the first occurence. If you want to replace them all, use a Regular Expression.
So you should have this :
function format() {
var text = document.getElementById("formatArea").value;
text = text.replace(/\n/g, "<br/>");
document.getElementById("resultArea").value = text;
}
The g ("global") flag on a regular expression is used to match all occurences.
Replace all was something I didn't understand when I started learning JavaScript too!
TL;DR There isn't a replaceAll function in JavaScript. But replace accepts something called regular expressions.
To replace all foos with bars in a string you have to do .replace(/foo/g, "bar"). /foo/g will match all the "foo"s and will replace them with bar. g is called flag and it it means global, meaning you match them all.
If you want to replace \ns you have to do: .replace(/\n/g, "<br/>"), like we did for foo:
text = text.replace(/\n/g, "<br/>")
Also, you have to assign the new string to the old string, as replace would not modify the original variable value:
function format() {
var text = document.getElementById("formatArea").value;
text = text.replace(/\n/g, "<br/>");
document.getElementById("resultArea").value = text;
}
<textarea rows="20" cols="80" id="formatArea">
</textarea>
<textarea rows="20" cols="80" id="resultArea">
</textarea>
<button onclick="format()">Click to create HTML breaks</button>
Use /\n/g for global replace and you have also missed the assignment of the changed text value in text itself, thus the replaced text was not taking effect. You need to assign the replaced value like text = text.replace(/\n/g, "<br/>"); :
function format() {
var text = document.getElementById("formatArea").value;
text = text.replace(/\n/g, "<br/>");
document.getElementById("resultArea").value = text;
}
asd
<textarea rows="20" cols="80" id="formatArea">
</textarea>
<textarea rows="20" cols="80" id="resultArea">
</textarea>
<button onclick="format()">Click to create HTML breaks</button>

HTML/Javascript/jquery function Button to place comma at end of each line in TextArea

I currently have a little HTML window I use at work to automatically Capitalize All, Alphabetize, and Capitalize first letters of contents entered into a <TextArea> on the HTML. I was hoping to find a method to add an additional "Comma" Button (<input type="submit">) - so it will automatically add a comma to the end of each line in the <TextArea>.
This should do what you are trying to accomplish.
function comma(){
var textarea = document.getElementById('textarea').value;
var res = textarea.replace(/(\r\n|\n|\r)/gm,",\r\n");
console.log(res);
document.getElementById('textarea').value = res;
}
textarea {
width: 500px;
height: 500px;
}
<textarea id="textarea"></textarea>
<button onclick="comma()">Comma</button>
Steps
Put the content of the textarea in a variable, say 'textareaContent'
Find all occurrences of "\r\n" and replace with ";\r\n"
EDIT.
HTML + JS
<script>
function addComma()
{
// get textarea's content
var content = document.getElementById('myTextArea').value;
// replace all newline's with ';\n'
var replaced = content.replace(/\n/g,';\n');
// rewrite the content with the new content
document.getElementById('myTextArea').value = replaced; }
</script>
<textarea id='myTextArea' rows='5' cols='30'>
First Line
Second Line
Third Line
</textarea>
<input type='button' onclick='addComma()' value='Add Comma' />
Anyways, this is an example, in live action. See the fiddle here -- http://jsfiddle.net/u6b7yz21/
Cheers.

Get String from the text box and apply to string properties

I have added one text box . I am getting the text entered text box like :
var text = document.getElementById("textarea").value;
then by using split function I am getting one particular String from say first string from the text . And tried to apply string properly on that like :
var split = text.split(" ");
var word = split[0];
word.italics();
then I formed text again with changed properties of first string and reassigned it to the text box
document.getElementById("textarea").value = text;
but those string properties are not applying to the word . same issue with all string properties like font color ,link etc . I dont know whats wrong I am doing ?
You cannot format text in a textbox
Try
document.getElementById("someContainerLikeADivOrSpan").innerHTML=text
For example
Live Demo
window.onload=function() {
document.getElementById("text").onkeyup=function() {
var text = this.value;
var split = text.split(" ");
var word = split[0];
document.getElementById("output").innerHTML=word.italics();
}
}
using
<textarea id="text" placeholder="type some words"></textarea>
<span id="output"></span>
You should use a div,span or p element to get the italics word. Try this,
HTML
<textarea id="textarea">test the italics now.</textarea>
<div id="div"></div>
SCRIPT
text=text.replace(word,word.italics());// replace the first word with italics
document.getElementById("div").innerHTML = text;// use div not textarea
Demo

Get inner text and split it. Javascript problems using innerHTML and split

Having the next simple html code:
<div id="content">
This is a test
</div>
I don't understad why this is OK:
$(function(){
text = 'this is a text';
word = text.split(' ');
alert(word[1])
})
but this is not:
$(function(){
text = $('#content').text();
word = text.split(' ');
alert(word[1])
})
Jquery or native javascript, the problem is the same. I expect an alert with the same word in both cases, but only occurs in the first one. Where is my mistake?
Here is my problem:
http://jsfiddle.net/bbtdf/2/
Thanks!
Try this (You need to trim the text)
$(function(){
var text = $.trim($('#content').text()),
word = text.split(' ');
alert(word[1])
});
DEMO.
You need to trim the text/html because they will have spaces before and after the content
$(function(){
var text = $('#content').text(),
word = $.trim(text).split(' ');
console.log(word[1])
})
Demo: Fiddle
Else you need to write your html as <div id="content">This is a test</div>
Try with this code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<div id="content">
This is a test
</div>
<script>
$(function(){
text = $('#content').text();
word = text.split(' ');
alert(word[1])
});
</script>
You have 3 spaces for indentation in the content. The text function is returning the second space in the alert for this case, so it is seen blank.
Remove the indentation/spaces before the content, you should see the expected result.

Categories

Resources