Find part of word before caret in textarea - javascript

I have a jQuery plugin that finds the caret position of a textarea. I implement it on the keyup function of the textarea, like this:
$("#editor").keyup(function () {
var textbox = $(this);
var end = textbox.getSelection().end;
});
I am wanting to find the word, or part of a word, before the caret. Words are delimited by any type of whitespace.
My main difficulty in doing this is dealing with line breaks. How can I find the word or part of a word immediately before the caret given the character index of the caret?

If you're using my jQuery textarea plug-in for this, the selection character positions are always relative to the value property of the textarea, regardless of how the browser handles line breaks. You could then get the last word as follows:
Note that you have to use the textarea's value property and not jQuery's val() method, which normalizes line breaks.
$("#editor").keyup(function () {
var textbox = $(this);
var end = textbox.getSelection().end;
var result = /\S+$/.exec(this.value.slice(0, end));
var lastWord = result ? result[0] : null;
alert(lastWord);
});

Related

How to get the line number based on substring in codemirror?

I need to get the line number of specific string in the textarea which has codemirror plugin.
var editor= CodeMirror.fromTextArea(document.getElementById("refstyle");
var doc = editor.getDoc();
var cursor = doc.getCursor(); // gets the line number in the cursor position
var line = doc.getLine(cursor.line); // get the line contents
editor.getSelection(line number) //it will select the text based on line number
So, How can I get the line number based on string (I expect something like doc.getLine(string) or doc.getSelection(String))
Is there any function to get the line number based on the string or to get searched string selected based on line number in the textarea? Pls help!
To search inside a CodeMirror instance, use the searchcursor addon. It'll give you the line/char position of matches.

Replace whole words only using Regex

I am trying to replace some letters in a textarea with some text from an input box.
The problem that I am facing is that it replaces all the values that are specified in CN.
For example, if CN is "A", then "A" will be replaced as well as "A" in "Apple". I want to replace only "A". I have tried using chordName = CN + " ", but that replaces values only where CN is in the middle of a sentence, not at the beginning of a line.
This is my code:
function doit(CN, SC) {
var rawLyrics = document.getElementById("ttbox").value;
var chordName = CN;
var spnCode = SC;
var res = rawLyrics.replace(new RegExp(chordName, 'g'), spnCode);
results.innerText = res;
}
I also have the problem where "results" textarea gets refreshed with the replaced words rather than changing only the required words i.e, I am using the above code to replace different words in a single block of text, so once I replace one word, and move on to the next, the previously replaced word comes back to it's previous state.
What am I doing wrong? Any solutions?

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"), ""));

javascript dynamic css styling

I'm trying to get all characters after "."(dot) and set some styling to them with JavaScript.
Example: $10.12 . I want to set some styling to numbers "12".
I have this number dynamically created in phtml file inside span.
I tried something like this, but without success:
var aa = document.getElementById('testdiv').innerHTML; // gets my span
var bb = aa.toString().split(".")[1]; // gets all numbers after "."
bb.setAttribute("style","width: 500px;");
Thanks to everyone! You really helped me. I would vote for every answer, but unfortunately I can't vote yet.
Your mistake begins here:
var aa = document.getElementById('testdiv').innerHTML; // gets my span
That's not your span, but its HTML contents. To take care of setting the width, you need something like this instead:
var aa = document.getElementById('testdiv'); // gets my span
aa.style.width = "500px";
You can only apply styling to HTML elements, not text nodes.
Try this instead:
var elem = document.getElementById('testdiv');
var parts = elem.innerHTML.toString().split(".");
parts[1] = "<div style=\"width: 500px\">" + parts[1] + "</div>";
elem.innerHTML = parts.join(".");
I've used because it's immediately apparent that a style has been applied, but if you want the number to appear consistent, as in "$10.12" without the "12" on a new line, you will probably need to apply additional styles or rethink how you're outputting the HTML.
You cannot set style to the textNode, the work around is to create an element to wrap the character after "." by using span. The idea is simple. First split it by "." and check if it has "." inside, if yes, create an element to wrap it and set style. Finally, join it back by "."
var inner = document.getElementById('testdiv').innerHTML;
var arr = inner.toString().split(".");
if(arr.length > 1)
{
arr[1] = '<span style="display: inline-block; width: 500px;">' + arr[1] + '</span>';
}
newContent = arr.join(".");
document.getElementById('testdiv').innerHTML = newContent;
You could do something like this:
document.getElementById('testdiv').innerHTML = document.getElementById('testdiv').innerHTML.replace( /(\d+).(\d+)/, '$1.<span id="end">$2</span>' );
document.getElementById('end').style.fontWeight = 'bold';
jsFiddle example
Your example fails at bb.setAttribute since you're trying to set an attribute on a string instead of a node. What you need to do is essentially rebuild the 10.12 with <span> elements surrounding the text you want to alter, and then you can use other JavaScript methods to modify the styling. The method you were using was almost correct, except the last part won't work because the split() method returns a string, not a node.
You can do this with regexp:
onlyDigitsText = text.replace(/\.([0-9]*)/g, ".<span class='highlighted'>$1</span>");
JsFiddle example
Try
var elem = document.getElementById('testdiv');
elem.innerHTML = elem.innerHTML.replace( /(\d+)\.(\d+)/g, '$1.<span class="decimalPart">$2</span>' );
// (\d+) one or more digits
// \. a dot character. Must be escaped otherwise it means ANY character
// (\d+) one or more digits
// g regex flag to replace all instances, not just one.
Then in your css add styling for the decimalPart class
.decimalPart {
width: 500px;
}
This has the added advantage of separating your styles from your html.
UPDATE
Following your comment to get the character just before the number use
elem.innerHTML.replace( /(\s)([^\s\d]*?)(\d+)\.(\d+)/g, '$1<span class="currencySymbol">$2</span>$3.<span class="decimalPart">$4</span>' );
// (\s) space, tab, carriage return, new line, vertical tab, form feed
// ([\s\d]*?) any set of characters that are not a digit or the above zero or more times
// (\d+) one or more digits
// \. a dot character. Must be escaped otherwise it means ANY character
// (\d+) one or more digits
// g regex flag to replace all instances, not just one.
Please note I have made an allowance for currency symbols that take up more than a single character.

Replace text in textarea using 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.

Categories

Resources