Replace text in textarea using Javascript - javascript

I need to replace all the matches of a regular expression till the caret position in a textarea using Javascript.
For example, if the text in the textarea is: "6 students carry 2 books to 5 classes" and the cursor
is placed on books and the regular expression is /\d/, the numbers 6 and 2 should be replaced by, say, 4.
I know the replace function and I know how to get the caret position, but how do I solve this problem?
Thanks for any help in advance!

textareaClicked = function(e){
var pos = e.target.selectionStart;
var beforeSelection = e.target.innerHTML.slice(0,pos);
var afterSelection = e.target.innerHTML.slice(pos);
var newHTML = beforeSelection.replace(/\d/g,4) + afterSelection;
e.target.innerHTML = newHTML;
e.target.setSelectionRange(pos,pos);
};
document.getElementById('foo').onclick=textareaClicked;
see it in action in this jsfiddle.

There is probably a more elegant way, but I would just copy the text from the text area, split the string into two substrings at the caret position (which you said you know how to find), do the replace on the first substring and then concatenate it with the second substring. Copy it back into the text area making sure to update the caret position appropriately.

Related

regex to separate paragraphs by double new line

Making a tiny helper for authors to add/remove empty lines in textarea. The one that removes extra lines seems to work:
if(jQuery("#remove_line").prop("checked")){
conver = conver.replace(/^\s*[\r\n]/gm,'');
}
But there has to be a reverse one that makes any new line into double new line (no matter if there's just 1 or even 3 new lines in a row). E.g. this:
text
text
text
text
Should be processed into this:
text
text
text
text
Anyone can help with that? Thanks in advance!
You can match one or more newlines [\r\n]+ and replace with 2 newlines \n\n
const regex = /[\r\n]+/gm;
const str = `text
text
text
text`;
console.log(str.replace(/[\r\n]+/g, `\n\n`));
didn't test but i think this could work : replace(/[\n]+?/g,'\n\n')
\n+ will match 1 or more new lines, the question mark will force to take the shortest amount possible (this will stop the matching block at the first non new line character)
The reverse?
addEventListener('load', ()=>{
const ta = document.querySelector('textarea');
function doubleSpaceAfter(fullText, text, insensitive = true){
const s = insensitive ? 'i' : '';
return fullText.replace(new RegExp('('+text+')\\s+', 'g'+s), '\n\n$1\n\n');
}
ta.value = doubleSpaceAfter(ta.value, 'text here');
}); // end load
<textarea>other stuff text here is this what you want? text here text here</textarea>

JavaScript: Replace certain occurrence of string depending on selection index

I've created my own autocomplete feature and I've come across a bug I'd like to fix. Here's an example of an incomplete sentence I might want to autocomplete the final word for:
let text = 'Hello there, I am her'
In my functionality the user clicks ctrl + enter and it autcompletes the word with a suggestion displayed on the page. In this case let's say the suggestion is 'here'. Also my controller knows where the user is based on the insertion cursor (so I have the index).
If I use replace like so:
text.replace(word, suggestion);
(Where word is 'her' and suggestion is 'here') it will replace the first occurrence. Obviously there are endless combinations of where this word might be in the text, how do I replace one at a certain index in text string? I know I can do it through some messy if conditions, but is there an elegant way to do this?
(If it is relevant I am using angular keydown/keyup for this)
EDIT>>>>>
This is not a duplicate on the question linked as in that case they are always replacing the last occurrence. If I did that then my program wouldn't support a user going back in their sentence and attempting to autocomplete a new word there
So, you have a position in a string and a number of characters to replace (=length of an incomplete word). In this case, would this work?
let text = 'appl and appl and appl'
function replaceAt(str, pos, len, replace) {
return str.slice(0, pos) + replace + str.slice(pos + len);
}
console.log(replaceAt(text, 0, 4, 'apple'))
console.log(replaceAt(text, 9, 4, 'apple'))
Gonna point you in a direction that should get you started.
let sentence = 'Hello lets replace all words like hello with Hi';
let fragments = sentence.split(' ');
for (let i=0; i<fragments.length; i++){
if(fragments[i].toLowerCase() == 'hello')
fragments[i] = 'Hi'
}
let formattedsentence = fragments.join(' ');
console.log(formattedsentence); //"Hi lets replace all words like Hi with Hi"

How remove a line of a string in Java Script

I would like to remove a specific line of a string using the replace.
If it is not possible with a replace, like some suggestion how i can delete a line, for example, my text have 3 lines, and i need remove line 2 or line 3... Why I can make this?
this is my first line and here this is my second line -> i need
delete this line here is another line
replace( "and here this is my second line", WHAT I NEED USE HERE TO REMOVE THIS LINE );
Solution is use splice first and join after remove line:
var str="this is my first line\nand here this is my second line -> i need delete this line\nhere is another line";
ar=str.split('\n'); ar.splice(1,1); str=ar.join('\n'); // This remove line 2
ar=str.split('\n'); ar.splice(2,1); str=ar.join('\n'); // This remove line 3
console.log(str);
Given that
var text = "";
text += "this is my first line\n";
text += "and here this is my second line\n";
text += "here is another line\n";
If you need to remove the first occurrence of the string use this:
text = text.replace("and here this is my second line\n", '');
And if you need to remove all the occurrences of the string use this one:
text = text.replace(/and here this is my second line\n/g, '');
Take into account that in the second example regular expression are used.
\n is the special character for line breaks and might be in different positions in your specific code
You can simply remove the line by replacing the target line with an empty string.
$(.someDivClass).text().replace("text to replace", "");
However I don't think it would completely remove the element containing that text, if that's what you're looking for.
With standard JS, you use this snippet in a method and make some action trigger that event such as a button click:
if(document.getElementById("id of <p> tag").innerHTML == "specific text")
document.getElementById("id of <p> tag").innerHTML = '';
I am not sure what your intentions are with removing the text and whether or not you want to completely remove the element containing the text, so this is the best solution I can offer. If you explain what your intentions are and how it will be applied to your project, I can provide a better solution.

How to replace particular string from a multiline textarea using jQuery?

When i have string which consists of a single line, replace works just fine.
As soon as i type in some text into text area and press enter as for new line, replace won't work anymore.
var currentValue = $('#service-field').val();
$('#service-field').val(currentValue.replace("particular string",""));
What should I do?
Try this to make sure you capture all occurrences, and not just the ones on the first line:
$('#service-field').val(currentValue.replace(/particular string/g, ""));
Or with a variable:
var t = "particular string";
$('#service-field').val(currentValue.replace(eval("/" + t + "/g"), ""));

read characters and words in HTML text using javascript

consider that i am getting a HTML format string and
want to read the number of words & characters,
Consider, i am getting,
var HTML = '<p>BODY Article By Archie(Used By Story Tool)</p>';
now i want to get number of words and characters
above html will look like:
BODY Article By Archie(Used By Story Tool)
IMPORTANT
i want to avoid html tags while counting words or character
avoid keywords like ** ** etc..
Ex. words and character should be counted of : (for current example)
BODY Article By Archie(Used By Story Tool)
please help,
Thank You.
To give an example for adamantium's suggestion:
var e = document.createElement("span");
e.innerHTML = '<p>BODY Article By Archie(Used By Story Tool)</p>';
var text = e.textContent || e.innerText;
var characterCount = text.length;
var wordCount = text.split(/[\s\.\(\),]+/).length;
Update: Added other word-stop characters
Use a hidden HTML element that can render text like span or p
Assign the string to the innerHTML of the hidden element.
Count the characters using length property of innerText/textContent.
To read the word count you can
Split the innerText/textContent using empty space
Get the length of the returned array.
Algorithm:
Sweep through the entire html
Perform regex replaces
replace <.*> (regex for anyting tat stays withing <>)by nothing
replace /&nbsp/ by nothing
tip: can be done by replace function in javascript. hunt on w3schools.com
Now you have the clutter out!
then perform a simple word/character count

Categories

Resources