Trim white space before text in javascript - 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.

Related

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)

How to get Surrounding word in javascript or jquery?

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

JavaScript, the use replace

var text_source="<a href='c:/exam_file.xls' target='_blank'>file downdload</a>";
text_search="file";
text_source.replace(new RegExp(text_search, 'gi'),
"<span style='font-weight:bold'>" +
text.toLowerCase() + "</span>");
The "a tag" link address has also changed:
<span style='font-weight:bold'>file</span> download
But, It should look like this. I have to change the text value in the "a tag".
<span style='font-weight:bold'>file</span> download
I will address what I said in a second, but you can do this without a loop with just pure regex. Below is how I accomplished this:
var text_source = "<a href='c:/bilmem_ne_dosyasi.xls' target='_blank'>Dosya Downdload</a>";
text_search = "dosya";
var patt = new RegExp("(<a .*?>)(" + text_search + ")(.*?</a>)","gi");
var text_source = text_source.replace(patt, function(match, $1, $2, $3) {
return $1 + "<span style='font-weight:bold'>" + $2.toLowerCase() + "</span>" + $3;
});
document.write(text_source);
DEMO
​
Getting back to what I said earlier, however, html can be a very, very complex language, and although regex can be used to parse it, partially, it should not be used for large quantities of data. Some patterns are too intricate to match against.
To ensure that your RegExp runs only against the content of the elements, you will need to select all of the elements that you want to manipulate and check their contents.
As an example:
var regExp = /dosya/ig;
[].slice.call(document.getElementsByTagName('a'), 0).forEach(function(element) {
if(regExp.test(element.textContent)) {
element.innerHTML = element.textContent.replace(regExp, function(text) {
return '<span style="font-weight: bold">' + text.toLowerCase() + '</span>';
})
}
});
There is also a jQuery pseudo selector :contains that does a similar thing.
Whilst the replies about not using regexes with HTML or XML are on the whole, correct, you could use the following for simple cases where you don't have too many nested tags:
var text_source="<a href='c:/bilmem_ne_dosyasi.xls' target='_blank'>Dosya Downdload</a>";
text_search="(<[^>]*>[^<]*)(dosya)([^<]*<[^>]*>)";
var replaced = text_source.replace(new RegExp(text_search, 'gi'), "$1<span style='font-weight:bold'>$2</span>$3");

Categories