Javascript: Delete text after cursor - javascript

Have been trying to adapt a snippet of code I found that deletes 1 character forward in a block of text into a code snippet that deletes all text forward (i.e through the end) of the text block. I can make the length into a larger number (say 100) to capture most instances, but that does not seem as clean.
var sel = getSelectedRange();
var start = sel[0];
var length = sel[1];
setTextInRange(start, length == 0 ? 1 : length, "");
setSelectedRange(start, 0);
For example, if the text read "This is the sample text" and the cursor was in front of the word "is", the result would just be the word "This "
I am using this code in the Drafts app on iOS to process text - very new to this and first post, so hopefully I included all information...
Edit: The location of the Drafts app help page that details the functions being used.

Not sure I completely understood you but I've thrown a quick prototype together.
http://jsfiddle.net/5bLxjja9/
$("#Javascript_example").click(function(){
var x = $("#Javascript_example").val();
var newStr = []
for(var i = 0; i< curPosition();i++){
newStr.push(x[i]);
}
console.log(newStr.join(''));
$("#Javascript_example").val(newStr.join(''));
});
function curPosition()
{
var ctl = document.getElementById('Javascript_example');
var curPos = ctl.selectionStart;
return curPos;
}

Never used, nor completely sure what Drafts is but having a look at the function definitions you might just need to use a different one.
test = "The lazy brown dog" \\ (imagine brown was selected)
sel = getSelectedRange() \\ returns [10, 5] if i counted right...
if you want to delete "brown dog" you can't use the length returned by getSelectedRange you will need to determine the length of the entire string first.
length = getText().length
length = length - sel[1] \\ find the length you want
setTextInRange(sel[0], length, "")
hope this helps

Could you include the code for the functions getSelectedRange, setTextInRange & setSelectedRange? That would give me a better idea of what sel is.
You're right that setting length to 100 isn't that clean. What you want to do is dynamically get the length of the rest of the text & delete that. It could be that you just want to pass in sel.length, but I'm not too sure what sel is an array of.

Related

How to change the value of innerText at a particular index?

I am trying to change the string displayed in the frontend by using a function in javascript.
let displayword = document.getElementById("displayword”)
console.log(displayword.innerText) //apple
Say, I want the change the letter “l” to something else say “i” but keep the rest of the letters unchanged how do I go around this?
Things I have tried
displayword.innerText[3] = “i” // -----does nothing----
I am confused why the above code using index does nothing, while the below does something
dash.innerText += “i” //applei
Extra question: Why does the above code using =+ change the formatting of the innerText? I want to keep the large font but it changes to regular font of the element (here I am using h1).
Thank you:)
You should look at the String documentation, especially String.slice and String.substring
In many languages, Strings can't be modified directly. Instead you "change" it by creating a new string composed of parts of the original.
As for how you'd do it in your case:
var text = displayWord.innerText;
text = text.slice(0, 3) + 'i' + text.slice(4) // apple -> appie
displayWord.innerText = text;
[Edited code slightly]
displayword.innerText = displayword.innerText.replace(oldCharacter, newCharacter);
To replace all occurrences:
displayword.innerText = displayword.innerText.replaceAll(oldCharacter, newCharacter);

Javascript Editing Text file - Remove all empty lines but one

I just started learning Javascript and I am trying to implement a project that came into my mind. The project is a simple text editor that takes a text as an input does some corrections and posts an output with the fixed text.
The input text is imported as an array. Each line of the text is an object property. The inputText is for displaying the default text in the browser inside a div, and the outputText is the one I use for the editing.
inputText = loadStrings("v.txt");
outputText = inputText;
Now the input text has some sentences. The problem is that there are a lot of empty lines in between.
firstLine
secondLine
thirdLine
What I want to achieve, is to remove all empty lines, but one, so the output text looks like:
firstLine
secondLine
thirdLine
I am searching for a solution for almost 3 days now. I have managed to remove ALL empty lines, but that's not what i want. I want to remove empty lines if they are more than one, but don't make any change if there is only one empty line.
This piece of code is one of many i have tried. This will remove ALL empty lines:
(source: Remove empty elements from an array in Javascript )
outputText = outputText.filter(function(e){
return e.replace(/[\r\n]+/g, '\n')});
Here is the codepen with all HTML, CSS and the JS code I am using.
https://codepen.io/theokondak/pen/KrNNVz
Try this regex:
e.replace(/([\r\n]){2,}/g, '\n\n')});
This will only match two or more consecutive empty lines replacing by an empty line.
My test code:
var lines = 'firstLine\n\n\n\nsecodLine\n\n\n\n\n\n\nthirdLine';
/*
firstLine
secondLine
thirdLine
*/
console.log(lines.replace(/([\r\n]){2,}/g, '\n\n'));
/*
firstLine
secodLine
thirdLine
*/
Try:
outputText = outputText.filter(function(e){
return e.replace(/[\r\n]+/g, '\n\n')});
I am not sure about the filter function above. but try below one must work.
outputText = outputText.replace(/[\r\n]+/g, '\n\n');
replacing with two new lines is the simplest way. you will get what you want.
I don't know if loadStrings leaves newlines at the end of the line or not. I'll assume it does (based on some code I see on this page). If it ends up mangled, please say so.
It is definitely easier to do this on a single string, like Hélio Márcio Filho says. So in your case, where you start with an array, you could just join the array together,replace three or more newlines with just two, then split it back up into lines:
let outputText = inputText.join('').replace(/(?:\r?\n){3,}/g, '\n\n').
split(/\n/).map(line => line + "\n");
But you can also do it just with filter - you just need to know how many empty lines you just saw, and suppress the extra ones:
let empties = 0;
let outputText = inputText.filter(line => {
if (line.replace(/[\r\n]+/, '')) empties = 0;
else empties++;
return empties <= 1;
});
The other answers work with a single string, but you're using the loadStrings() function from Processing.js, which gives you an array of strings.
You could convert the array into a single string, or load the file as a single string, but it seems simplest to me if you just process the array. Something like this:
function reduceNewlines(inputArray){
var outputNewArray = [];
var previousLineWasNewline = false;
for(var i = 0; i < myArray.length; i++){
if(myArray[i] == ''){
if(!previousLineWasNewline){
outputArray.push('');
}
previousLineWasNewline = true;
}
else{
outputArray.push(myArray[i]);
previousLineWasNewline = true;
}
}
return outputArray;
}
Please note that I haven't tested this code, and there is probably a ton of room for improvement. But the general idea is there: you could write a function that processed the array and returned a new array with the consecutive newlines removed.
You might also consider pre-processing your text file so you don't have to do this at all.
First of all, I would like to thank everyone for trying to help. I studied all your replies, I've tested each of them and they all work (some with needed tweaking) as stand-alone code, but when I inserted them into my code, some things went wrong. So I struggled and came out with my own solution, which is greatly inspired by your comments.
So the code that worked in my case is :
function reduceNewlines(outputTextEditNewLines) {
for (let key = 0; key < outputTextEditNewLines.length; key++) {
if (outputTextEditNewLines[key] == '') outputTextEditNewLines[key] = '\n';
else outputTextEditNewLines[key] = outputTextEditNewLines[key];
}
arrayToString = outputTextEditNewLines.join(""); // convert object myArray to string
console.log(arrayToString.replace(/([\r\n]){1,}/g, '\n\n')); // exports the text as it should
return arrayToString.replace(/([\r\n]){1,}/g, '\n\n');
}
The console.log exports the text as it should. Now the next step for my project is to make this string print to the DOM as it prints in the console.log.

How to find a substring only in the text portion of an HTML string, with Javascript?

UPDATE: I am no longer specifically in need of the answer to this question - I was able to solve the (larger) problem I had in an entirely different way (see my comment). However, I'll check in occasionally, and if a viable answer arrives, I'll accept it. (It may take a week or three, though, as I'm only here sporadically.)
I have a string. It may or may not have HTML tags in it. So, it could be:
'This is my unspanned string'
or it could be:
'<span class="someclass">This is my spanned string</span>'
or:
'<span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>'
or:
'<span class="no-text"><span class="silly-example"></span></span><span class="some-class">This is my spanned string</span>'
I want to find the index of a substring, but only in the portion of the string that, if the string were turned into a DOM element, would be (a) TEXT node(s). In the example, only in the part of the string that has the plain text This is my string.
However, I need the location of the substring in the whole string, not only in the plain text portion.
So, if I'm searching for "span" in each of the strings above:
searching the first one will return 13 (0-based),
searching the second will skip the opening span tag in the string and return 35 for the string span in the word spanned
searching the third will skip the empty span tag and the openings of the two nested span tags, and return 91
searching the fourth will skip the nested span tags and the opening of the second span tag, and return 100
I don't want to remove any of the HTML tags, I just don't want them included in the search.
I'm aware that attempting to use regex is almost certainly a bad idea, probably even for simplistic strings as my code will be encountering, so please refrain from suggesting it.
I'm guessing I will need to use an HTML parser (something I've never done before). Is there one with which I can access the original parsed strings (or at least their lengths) for each node?
Might there be a simpler solution than that?
I did search around and wasn't been able to find anyone ask this particular question before, so if someone knows of something I missed, I apologize for faulty search skills.
The search could loop through the string char by char. If inside a tag, skip the tag, search the string only outside tags and remember partial match in case the text is matched partially then interrupted with another tag, continue the search outside the tag.
Here is a little function I came up with:
function customSearch(haysack,needle){
var start = 0;
var a = haysack.indexOf(needle,start);
var b = haysack.indexOf('<',start);
while(b < a && b != -1){
start = haysack.indexOf('>',b) + 1;
a = haysack.indexOf(needle,start);
b = haysack.indexOf('<',start);
}
return a;
}
It returns the results you expected based in your examples. Here is a JSFiddle where the results are logged in the console.
Let's start with your third example:
var desiredSubString = 'span';
var entireString = '<span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>';
Remove all HTML elements from entireString, above, to establish textString:
var textString = entireString.replace(/(data-([^"]+"[^"]+")/ig,"");
textString = textString.replace(/(<([^>]+)>)/ig,"");
You can then find the index of the start of the textString within the entireString:
var indexOfTextString = entireString.indexOf(textString);
Then you can find the index of the start of the substring you're looking for within the textString:
var indexOfSubStringWithinTextString = textString.indexOf(desiredSubString);
Finally you can add indexOfTextString and indexOfSubStringWithinTextString together:
var indexOfSubString = indexOfTextString + indexOfSubStringWithinTextString;
Putting it all together:
var entireString = '<span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>';
var desiredSubString = 'span';
var textString = entireString.replace(/(data-([^"]+"[^"]+")/ig,"");
textString = textString.replace(/(<([^>]+)>)/ig,"");
var indexOfTextString = entireString.indexOf(textString);
var indexOfSubStringWithinTextString = textString.indexOf(desiredSubString);
var indexOfSubString = indexOfTextString + indexOfSubStringWithinTextString;
You could use the browser's own HTML parser and XPath engine to search only inside the text nodes and do whatever processing you need.
Here's a partial solution:
var haystack = ' <span class="no-text"></span><span class="some-class"><span class="other-class">This is my spanned string</span></span>';
var needle = 'span';
var elt = document.createElement('elt');
elt.innerHTML = haystack;
var iter = document.evaluate('.//text()[contains(., "' + needle + '")]', elt).iterateNext();
if (iter) {
var position = iter.textContent.indexOf(needle);
var range = document.createRange();
range.setStart(iter, position);
range.setEnd(iter, position + needle.length);
// At this point, range points at the first occurence of `needle`
// in `haystack`. You can now delete it, replace it with something
// else, and so on, and after that, set your original string to the
// innerHTML of the document fragment representing the range.
console.log(range);
}
JSFiddle.

Detect Once a Certain Word Has Just Been Entered in a Textarea

Considering features like EditArea's and CodeMirror's autocomplete, I was wondering if, like Dreamweaver, there is a way to detect if the last word you entered is in a certain list then provide the same kind of suggestion box but with the function's arguments. I imagine you would use a regular expression on the entire field or possibly split() the whole thing (or the current line) then use the length attribute of the array to find the last bit of text, then do something involving an indexOf-like operation; however, this seems like it would get a bit resource-intensive. It almost looks like I've answered my own question, but it always helps to fully explain one's quandary, especially publicly. There's gotta be a better solution than mine. I appreciate any input. Thank you.
Put the list of words to match in an object, have the text or options to display as the value. Then on keyup or keypress you can get the last word of the text area using a function like:
function showLastWord(id){
var el = document.getElementById(id);
var lastWord = el.value.match(/\w+$/);
return lastWord? lastWord[0] : '';
}
Then check if the word is in the list and do stuff appropriately.
Edit
A small example is:
<textarea onkeyup="showHelp(this);"></textarea>
<script>
var getLastWord = (function() {
re = /\w+$/;
return function (s){
var lastWord = s.match(re);
return lastWord? lastWord[0] : '';
}
}());
var keyWords = {foo:'foo was typed',bar:'bar was typed'};
function showHelp(el) {
var lastWord = getLastWord(el.value);
// Check for matching own property of keyWords
if (keyWords.hasOwnProperty(lastWord)) {
// Do stuff
console.log(keyWords[lastWord]);
}
}

Returning a string from a parallel array

I am sorry for the very newbie question, but this is driving me mad.
I have a word. For each letter of the word, the characters position in one array is found and then returns the character at the same position found in a parallel array (basic cipher). This is what I already have:
*array 1 is the array to search through*
*array 2 is the array to match the index positions*
var character
var position
var newWord
for(var position=0; position < array1.length; position = position +1)
{
character = array1.charAt(count); *finds each characters positions*
position= array1.indexOf(character); *index position of each character from the 1st array*
newWord = array2[position]; *returns matching characters from 2nd array*
}
document.write(othertext + newWord); *returns new string*
The problem I have is that at the moment the function only writes out the last letter of the new word. I do want to add more text to the document.write, but if I place within the for loop it will write out the new word but also the other text inbetween each word. What i actually want to do is return the othertext + newWord rather than document.write so that I can use it later on. (just using doc.write to text my code) :-)
I know its something really simple, but I cant see where I am going wrong. Any advice?
Thanks
Issy
The solution is to build newWord within the loop using += instead of =. Just set it to an empty string before the loop.
There are other problems with this code. Variable count is never initialized. But let's assume that loops should be using count instead of position as it's principal counter. In that case, if I am not mistaken, this loop will just generate array2 as newWord. First two lines of loop's body cancel each other in a matter of speaking, and position will always be equal to count, so letters from array2 will be used sequentially from beginning to the end.
Could you provide one example of input and desired output, so that we understand what you actually want to accomplish?
A good way of structuring your code and your question is that you define a function that you need to implement. In your case this could look like:
function transcode(sourceAlphabet, destinationAlphabet, s) {
var newWord = "";
// TODO: write some code
return newWord;
}
That way, you clearly state what you want and which parameters are involved. It is also easy to write automatic tests later, for example:
function testTranscode(sourceAlphabet, destinationAlphabet, s, expected) {
var actual = transcode(sourceAlphabet, destinationAlphabet, s);
if (actual !== expected) {
document.writeln('<p class="error">FAIL: expected "' + expected + '", got "' + actual + '".</p>');
} else {
document.writeln('<p class="ok">OK: "' + actual + '".');
}
}
function test() {
testTranscode('abcdefgh', 'defghabc', 'ace', 'dfh');
}
test();

Categories