Delete complete one string from a paragraph - javascript

I have a paragraph from which i want to delete a complete one string when user press single backspace.
For example like in yahoo mail. when we compose an email and write email address at "To or CC or BCC" section(s), when user press single backspace the complete email address is deleted.
I want that functionality but in paragraph.

Removing e-mail addresses on backspace is just a deletion of characters until you hit a space (or ; depends on your use case) char.
So basically what you are really asking here is:
How to substring the last portion of a string while the space character is the delimiter.
Here is a simple snippet as example:
EDIT:
I've updated the snippet to support caret (cursor) position while clicking the backspace or delete keys.
$('#delete').on('click', function(){
var $input = $('#mystring');
var nextStr = deleteUpToSpace($input.val());
$input.val(nextStr);
});
$('#mystring').on('keyup', function(e){
var currentCursorPoisitoin = this.selectionStart;
if(e.keyCode == 8 || e.keyCode == 46){ // backspace or delete keys
var $input = $(this);
var nextStr = deleteBasedOnPosition($input.val(), currentCursorPoisitoin);
$input.val(nextStr);
}
});
function deleteUpToSpace(str){
var index = str.lastIndexOf(" ");
var nextStr = str.substring(0, index);
return nextStr;
}
function deleteBasedOnPosition(str, position){
var strUpToPosition = str.slice(0, position);
var lastIndexOfSpace = strUpToPosition.lastIndexOf(" ");
var strToRemove = strUpToPosition.substring(lastIndexOfSpace, position);
var nextStr = str.replace(strToRemove, "");
return nextStr;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="mystring" value="this is a test string">
<button id="delete">Delete</button>

You probably want to remove a word when backspace is clicked.
You can use this code.
<!doctype html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
</head>
<body>
<textarea id="foo"></textarea>
<script type="text/javascript">
document.getElementById('foo').addEventListener("keydown",function(event){
if(event.code=="Backspace"){
var text=document.getElementById('foo').value;
var lastspace = text.lastIndexOf(" ");
var updateStr=text.substring(0,lastspace);
document.getElementById('foo').value=updateStr;
}
});
</script>
</body>
</html>

Firstly, you need to identify the separator that separates these different entities. For instance, if you need to remove the last sentence in a paragraph, the separator is the period (or full-stop, as some may call it).
Then, you can split the string by the separator, remove the last two elements (because the last element is essentially a non-completed) and then rejoin.
text.split('.').slice(0,-2).join('.') + '.'
If your separator was a period. Or generally,
text.split(separator).slice(0,-2).join(separator) + separator
See this JS Fiddle I made for demonstration: https://jsfiddle.net/tt24kfng/1/
An interesting thing you could try out would be to remove the last completed entity and keeping the last incompleted intact.

Related

Substring assignment

I have an assignment in school but I'm totally stuck.
My assignment:
Make a program that ask for a text and then write out the text several times. First with just one letter, then with two and so on. For example, if the user write "Thomas", your program should write out "T", "Th, "Tho, "Thom", and so on.
My hopeless attempt
I been trying to use "Substring" and a loop to make it work but I'm not sure I'm on the right path or not. Right now my code look like this:
<head>
<meta charset= "UTF-8"/>
<title> assignment14 - Johan </title>
<script type="text/javascript">
var text= test.length;
for (i=0;i< test.length;i++)
function printit()
{
var str = test;
var res = str.substring (i, 2);
document.getElementById("test").innerHTML = res;
}
</script>
</head>
<body>
<h1>Assignment 14</h1>
<form name="f1">
<input type="text" id="test" value="" />
<input type="button" value="Hämta" onclick="printit(document.getElementById('test'))" />
</form>
</body>
Just need some kind of hint If I'm going in the right direction or not, should I use some other functions? Very thankful for help.
You have to rewrite a script.When you want to extract one by one you can use substring(); function.
How to Call : StringObject.substring (StartPoint,endPoint);
Solution:
<script type="text/javascript">
function printit(){
var test=document.getElementById("test").value;
var text= test.length;
for (i=0;i<= text;i++)
{
var res = test.substring (i, 0);
document.write(res);
document.write("<br/>");
}
}
</script>
You are on the right way. substring(start,end) in javascript gives you the consecutive part of the string letters from start index to end. You just use it in a wrong way for your case. You have to call it like this:
substring(0,i)
You need to make few changes to your code:
1) use document.getElementById('test').value in printit function call at onclick as you have to send the value of the textbox instead of innerHTML.
2) Modify the printif function-
function printit(test)
{
document.getElementById('test').value=''; /*remove existing text from textbox*/
for (i=0;i< test.length;i++) {
var res = str.substring (0, i+1);
document.getElementById("test").value += ' '+res;
}
}
In printit function empty the text box and then append each substring to the existing text to get "T Th Tho Thom.." and so on
Hope this helps.
I don't use for-loop for this (whenever possible, I prefer functional style). Instead, I write a function that returns an array of substrings:
const substrings = string =>
Array.from(string).map((_, i) => string.slice(0, i + 1))
And here's a working codepen
Output several time using substring() method can be done as below, create a function which performs this task of extracting the user inputted string on button click using forloop and substring() method.
var intp = document.querySelector("input");
var btn = document.querySelector("button");
var dv = document.querySelector("div");
btn.onclick = function() {
var b = intp.value;
for (var i = 1; i <= b.length; i++) {
var c = b.substring(0, i);
dv.innerHTML += c + "<br/>";
}
}
div{
width:400px;
background:#111;
color:yellow;
}
<input type="text">
<button>Click</button>
<br/><br/>
<div></div>
You have used a correct way for doing this, but as one of user suggest the start and end value of substring() was not correct.

How to append the string to textarea using javascript

I want to append the given string to the textarea i have, i want to append the text in the way it should look like someone typing on the texture,because i have the voice playing in the background for 6 seconds which which says the same thing to be written.
<textarea id='typeable' style='font-size:18px;background:#F8E71C'></textarea>
<script>
function addText(event) {
document.getElementById("typeable").value += "Hello welcome to the new world of javascript"
}
</script>
how can i do this
Count the number of characters in the sentence, and then calculate the time for each char by dividing the total time with the no. of characters and then call the time Interval and run it until all the characters are printed.
Still you can decide the time taken to print each character and modify it as per your need. Please note that the time is taken in milliseconds.
var chars = "Hello welcome to the new world of javascript".split("");
var textarea = document.querySelector('textarea');
var total_time=6000;
var index = 0;
var time_per_char = total_time/chars.length;
var t = setInterval(function(){
textarea.value += chars[index];
index++;
if (index === chars.length){
clearInterval(t);
}
},time_per_char);
<textarea style="width:100%;background:#E1ECF4">
</textarea>
Code is attached below:
<!DOCTYPE html>
<html>
<script>
function appendText() {
document.getElementById("typeable").value= document.getElementById("typeable").value + "Hello welcome to the new world of javascript";
}
</script>
<body onload="appendText()">
<textarea id='typeable' style='font-size:18px;background:#F8E71C'></textarea>
</body>
</html>

Removing lines containing specific words in javascript

This script is supposed to take a list of links, transform some by changing some words and eliminate others containing specific string of characters.
The first part is ok. I need help with the second. The line
x = x.replace(/^.+/category/.+$/mg, "");
doesn't work even if we change the + with *. I used sources from here (1 & 2 ). So, help the noob.
<!DOCTYPE html>
<html>
<body>
<h3>Instert your links</h3>
input:<br>
<textarea id="myTextarea">
http://example.com/ad/123.html
http://example.com/ad/345.html
http://example.com/ad/3567.html
http://example.com/category/fashion.html
http://example.com/ad/8910.html
http://example.com/category/sports.html
</textarea>
<button type="button" onclick="myFunction()">Get clean links</button>
<p id="links"></p>
<script>
function myFunction() {
x = document.getElementById("myTextarea").value;
x = x.replace(/http:\/\/example.com\/ad\//g, "http://example./com/story/");
x = x.replace(/\n/g,"</br>");
x = x.replace(/^.+/category/.+$/mg, "");
document.getElementById("links").innerHTML = x;
}
</script>
</body>
</html>
I think you need to escape your forward slashes as you are also using them as the regex delimiter.
x = x.replace(/^.+\/category\/.+$/mg, "");
Assuming that you want to copy those lines in <p> remove line containing category in it.
change your function to
function myFunction() {
x = document.getElementById("myTextarea").value;
var lines = x.split("\n").filter( function(val){
return val.indexOf( "category" ) == -1;
});
document.getElementById("links").innerHTML = lines.join( "<br>" );
}

search() function of Javascript does not behave properly

I don't know why search() function returns 0 for any input with SPECIAL CHARACTER, I wanted to find position of 1st occurrence of special character. When I am hardcoding the value for search() method it is working fine, but when I am taking value from text box it is not working properly.
Following is my HTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<input type="text" id="txt" onkeyup="return checkLength();"/>
<input type="button" id="btn" value="Verify" onclick="getValue()"/>
</body>
</html>
Following is the script where I have implemented the use of search() of Javascript, but don't know why I am getting 0 value for any input. Actually I wanted to find the position of first special character occurrence.
$(document).ready(function() {
$('#btn').attr('disabled',true);
$("#txt").bind({
paste : function(){
$('#btn').attr('disabled',false);
checkLength();
},
cut : function(){
checkLength();
}
});
});
function checkLength(){
var txtLength = $("#txt").val().length;
var banTxt = document.getElementById("txt").value;
if (txtLength != 0) {
if(isAlphaNumeric(document.getElementById("txt").value)) {
$('#btn').attr('disabled',false);
} else {
var str=banTxt;
//Here I am using search() to find position of Special Character.
var n=banTxt.search(/[^a-zA-Z ]/g);
alert("position of special char is: " + n);
var preTxt = banTxt.substring(0,(txtLength - 1));
var preTxtLength = preTxt.length;
alert("Special characters are not allowed!");
if(preTxtLength == 0){
$('#btn').attr('disabled',true);
document.getElementById("txt").value = "";
}else if(preTxtLength != 0){
document.getElementById("txt").value = preTxt;
$('#btn').attr('disabled',false);
}
}
} else {
$('#btn').attr('disabled',true);
}
}
function isAlphaNumeric(inputString) {
return inputString.match(/^[0-9A-Za-z]+$/);
}
function getValue(){
var txtValue = document.getElementById("txt").value;
alert("Value submitted is: " + txtValue);
}
var n=banTxt.search(/[^a-zA-Z ]/g);
I tried with string with special characters like 123#4$5 , 12#4 , etc. and I am getting alert as position of special char is: 0
That's just what your regex matches: No alphabet characters and no blanks - that includes digits. In contrast, your isAlphaNumeric function matches against /^[0-9A-Za-z]+$/ - you probably want to align them with each other.
Actually i have used the following line var n=banTxt.search(/[^a-zA-Z ]/g); for getting the position of special char, at the same time please note that i have used onkeyup event so if i am copy pasting the code i.e first ctrl then v, ctrl + v then ctrl itself is keyup event i think this might be the reason i am getting 0 as position of special char, as after pressing ctrl no text is pasted but onkeyup event is triggered.
I am looking for the solution of it.

Camelcase using split( ) twice in Javascript

I am trying to make a function to split a sentence into words then split the words into characters and capitalize the first letter of each word. Yes it's homework and after many tries I can not get it to work. One thing tripping me up is using split() twice.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<head>
<title>Sentence Case Conversion</title>
<script type= "text/javascript">
/* <![CDATA[ */
/* ]]> */
</script>
</head>
<body>
<form name= "convertText">
<p>Enter text to convert to sentence case:</p>
<input type ="text" size ="120" name="userInput">
</br>
</br>
<input name= "Submit" onclick= "sentenceCase()" value= "Convert Text" type= "button">
</form>
</br>
</br>
</br>
<form name= "ouputText">
<p>Here is your converted text:</p>
<input type="text" size="120" name="result">
<script type= "text/javascript">
/* <![CDATA[ */
function sentenceCase() {
var userInput = document.forms[0].userInput.value; //get user input
var wordArray = userInput.split(" "); //split user input into individual words
for (var i=0; i<wordArray.length; i++) {
var characterArray = wordArray[i].split("");
characterArray[0].toUpperCase();
wordArray[i]=characterArray.join;
}
/* ]]> */
</script>
</body>
</html>
You're close:
> characterArray[0].toUpperCase();
That returns a value, it doesn't modify it in place
> wordArray[i]=characterArray.join;
join is a method, you have to call it. Also, it returns a value, it doesn't modify anything in place. You might consider using substring instead, but with the array you have:
var firstChar = characterArray.shift().toUpperCase();
var newWord = firstChar + characterArray.join('');
should do the trick.
toUpperCase() can't modify your variable in place; it returns the capitalized string. So:
characterArray[0] = characterArray[0].toUpperCase();
... but you could just use charAt() and substring(), too:
wordArray[0] = wordArray[0].charAt(0).toUpperCase() + wordArray[0].substring(1);
... and then you have to actually call join():
wordArray[i] = characterArray.join();
... and you'd probably want to pass that an empty string, or it'll default to a comma as a separator.
The fun way is 'hello world this is camel case'.replace(/\s(\S)/g, function($0, $1) { return $1.toUpperCase(); }), though.
Factor out the common elements into understandable pieces of code:
function toCamelCase(sentence) {
var words = sentence.split(" ");
var length = words.length;
for (var i = 1; i < length; i++)
words[i] = capitalize(words[i]);
return words.join("");
}
function capitalize(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
Now you can convert sentences to upper case. It's probably a good idea to remove punctuation marks from the sentence before converting it. Here are a few examples:
alert(toCamelCase("java script")); // javaScript
alert(toCamelCase("json to XML")); // jsonToXML
alert(toCamelCase("ECMA script")); // ECMAScript
The last one appears to be PascalCase but is still considered valid camelCase. You can see the demo here: http://jsfiddle.net/GhKmf/

Categories

Resources