How to get Surrounding word in javascript or jquery? - javascript

I am working with webview and loading the html pages in webview so here I got stuck somewhere, I want to use the javascript.here. I am explaing what I need exactly below:
I am having the html data like this-
"My selected the word "widget". But I'd like to know if the selection is after "red" or "blue". Is this possible? I've been scouring the Internet for some advice, and I'm having trouble finding an answer"
So suppose from above text I selected the text " selection is after"(which is shown bold) I need the previous words before this word and the words after this word in that line only. Suppose I select in line 2 so I need all the previous word in that line before the word and all words after the selected word in that line and in case if the selected word is in starting of line so return previous word as null and remaining word after the selected word up-to the end of line similarly for last word vice versa
Please tell we how to achieve it using JavaScript?

I created a solution in a JSFiddle at Selecting text before and after word
First I created a paragraph to hold the text to be selected
<p id="yourTextContainer">Lorem ipsum data sid amet</p>
Then, in the JavaScript, I split the paragraph into spans, placing the index of each word in the name attribute. Then, when a word is clicked it used the index to return all words before, and all words after.
var textindex;
var textbefore;
var textafter;
$(document).ready(function(){
var words=$("#yourTextContainer").text().split(' ');
$("#yourTextContainer").html("");
$.each(words, function(i,val){
//wrap each word in a span tag
$('<span name="'+ i+'"+ />').text(val +" ").appendTo("#yourTextContainer");
});
$("#yourTextContainer span").live("click",function(event){event.stopPropagation();
$("#yourTextContainer span").css("background-color","white");
$(this).css("background-color","blue");
//gets the text of clicked span tag
var textselected = $(this).text();
textindex = $(this).attr("name");
alert("You just selected "+textselected+" index " + textindex);
textbefore= "";
textafter = "";
$("span").each(function (index) {
// alert("LOOPING INDEX " + index);
if (index<(textindex))
textbefore = textbefore + $(this).text() + " ";
if (index>(textindex))
textafter = textafter + $(this).text() + " ";
});
alert("Text before is "+textbefore );
alert("Text after is "+textafter );
});
});
For example, if you click on "ipsum", the JS alerts, "Lorem" as the text before, and "data sid amet" as the text after "ipsum".
Hope this helps! You can also run the fiddle to see what I mean.

What about using match with a regular expression:
var pattern = /^(.+)(selection is after)(.+)$/;
match = "hello selection is after goodbye".match(pattern)
match[1] // hello
match[2] // selection is after
match[3] // goodbye

Related

Trim white space before text in javascript

Can't find the answer, I tried with what I found on this website and elsewhere but it never works.
Goal : to trim white spaces before and after a word giving in the field DIV.
Problem : everything works fine as long there is NO white space before a word ! There can already be text in the DIV of it can be an empty DIV where text can be inserted.
I tried in the javascript in the DIV like trim(this) but that doesn't work. Even inthe script itself I tried $.trim(editableObj.innerHTML) , nor editableObj.innerHTML.trim()
Nothing works !
JS
<script>
function showEdit(editableObj) {
$(editableObj).css("background", "#FFF");
}
function saveToDatabase(editableObj, column, linkmainid, nav, linkid) {
$(editableObj).css("background", "#FFF url(loaderIcon.gif) no-repeat right");
$.ajax({
url: 'save'+nav+'.php',
type: "POST",
data: 'linkcat=' + column + '&linktitle=' + editableObj.innerHTML + '&linkmainid=' + linkmainid + '&action=' + nav + '&linkid=' + linkid,
success: function(data) {
$(editableObj).css("background", "#FDFDFD");
window.location="/website/cms/menu.php";
}
});
}
HTML
<div class="navnew" contenteditable="true" onBlur="saveToDatabase(this,'1','999999','navnew','111')" onClick="showEdit(this);"></div>
var stringWithLeadingSpaces = " hello world!"
var trimmedString = stringWithLeadingSpaces.trim();
console.log(trimmedString); //logs "hello world!"
trim
Add this snippet to your code:
String.prototype.trim = String.prototype.trim || function trim() {
return this.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); };
Then, use:
var myValue = " one, two, three ".trim();
or
var myValue = " one, two, three ";
var myValueTrimmed = myValue.trim();
Typing spaces into the content editable DIV inserts non breaking space characters. If you retrieve the content of editableObj.innerHTML these show up as sequences of the character entity string " ". Naturally String.prototype.trim does not remove occurrences of " " because they are not white space text!
If you retrieve the content as editableObj.textContent the text returned contains actual non-break spaces with character code 0xA0. String.prototype.trim does remove these.
Ultimately choose a trim method that suits your needs, depending on whether you want to save HTML or plain text in the database.

How can I format text in an HTML <textarea>?

I have a <textarea> on my page, and when I click a button, the value of the text in the textarea is assigned to .innerHTML of a paragraph on my page.
Now let's say I type something like this in the textarea:
Hey
how's
it
going
?
The paragraph would look like this
Hey how's it going ?
Basically, it wouldn't have <br> tags at the end of each row. Is there a way I can force the JavaScript function to insert <br> tags at the end of each row of my textarea, or is there an easier way to do this?
JavaScript code:
document.getElementById("sendMsgBtn").onclick = function(){
var element = document.createElement("p");
element.style.borderBottom = "1px solid black";
var content = document.createTextNode(document.getElementById("currentMsg").value);
content = content.replace(/\n/g, "<br>");
element.appendChild(content);
document.body.appendChild(element);
document.getElementById("currentMsg").value = "";
}
You don't want line breaks. Trust me.
Just set this:
white-space: pre-wrap;
This CSS will make whitespace significant, preserving it as it was typed.
When you copy the element from the textarea to the paragraph tag, replace all line breaks with <br> tags:
var input = document.getElementById("myTextarea").innerHTML; // get textarea contents
input = input.replace( /\n/g, "<br>"); // replace line breaks with <br> tags
document.getElementById("myParagraph").innerHTML = input; // place html-ified input into your <p>
If you are using jQuery, try this:
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
Then nl2br(yourVariableWithContent); can be used to change newline characters (the ones that the return button makes) into <br/>.

how to replace a string in javascript after the specific index

Hi I am having the string which contains html content and I want use javascript to replace the tag <p class="MsoNormal"> with '' empty space and i want to replace corresponding closing tag </p> with <br> tag in that string.
If I use
first line:
str=str.replace(/<p class=\"MsoNormal\">/g,'');
second line: str=str.replace(/<\/p>/g,'<br>');
All the closing </p> tag get remove .But i want to replace the closing </p> tag which has the opening tag of "<p class="MsoNormal">".
The first line of script is okay of me .What should i use to replace that corresponding closing tag in the second line.
Check this: Output is what I got from your question is to replace with Empty String
var replaceTag = function(str, replaceTagString, endTagString) {
var str = '';
while(str.indexOf(replaceTagString) != -1) {
//search for </p> after my matched String
var indexOfClosingTag = str.indexOf(endTagString, str.indexOf(replaceTagString))
//Replace </p> using Substring
str = str.substr(0,indexOfClosingTag) + "<br>" + str.substr(indexOfClosingTag + endTagString.length,k.length)
//Replace your main String
str = str.replace(replaceTagString,'')
}
return str
}
var k = "<p class='MsoNormal'>something</p><p>other p tag</p><h1>I am h1</h1><p>Hello p</p><p class='MsoNormal'>Replace My Tag too</p>"
replaceTag(k, "<p class='MsoNormal'>", "</p>")
Output:
"something<p>other p tag</p><h1>I am h1</h1><p>Hello p</p>Replace My Tag too"
Concept:
string.indexOf(searchvalue,start)
Start searching for End of the Tag (P) after my current matched string position
Define a function yourself like this-->
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
And use it like this:
str = str.replaceAt(3, "</p>");

type in empty divs while contenteditable = true?

why won't the cursor enter some of my divs when contenteditable is enabled?
also, why does my browser tell me there is nothing in the div when there is clearly a space character in it?!
var div = '<div> </div>';
div.innerHTML = undefined
What gives?
contenteditable does not apply to empty elements, so you may want to insert a non-breaking-space character into the empty elements you want to be able to edit
the non-breaking-space " " will act as a character when left on its own,
whereas a whitespace " " will only count as a character if placed after another character
<div>" "</div> ----------------> innerHTML = undefined
<div>" "</div> --------> innerHTML =
the gray box around means its an html character
so make sure you insert a "&nbsp" and not a " "
var nbsp = " ",
div = document.getElementById('id');
div.innerHTML = nbsp
jquery works too
var div = $('div#id')
div.html(nbsp1)

forms and javascript

I have a form button and I want 2 lines of text. In the form I have this
value='".$row['item'].'
$'.$row['price']."'
and I get
Hot Dog
$1.00
I want to update this in JavaScript and tried this
sBtn = itm + "
$" + prc;
document.getElementById(conbtn).value = sBtn;
and
sBtn = itm + "<br>$" + prc;
document.getElementById(conbtn).value = sBtn;
without success. The first gives
Hot Dog
$1.00
and the second
Hot Dog<br>$1.00
Any idea how to write 2 lines from JS?
I got it. Used
sBtn = itm + "\r\n$" + prc;
If you have a form input button, use an escaped newline in the value property.
document.getElementById(conbtn).value = "Test 1\nTest 2";
If you have a button tag element, use a break element in the innerHTML property.
document.getElementById(conbtn).innerHTML = "Test 1<br/>Test 2";

Categories