Javascript / Jquery+ Replace single and double quotes in a inner html content - javascript

Let's say I have a DIV as below.
<div id="mydiv">
<p class="abc">some text here</p>
<p class="xyz"><img src="img.jpg" title="my img"/> some "double quoted text" here</p>
</div>
I read the inner html of the div.
var originalcontent = $("mydiv").html();
Now I need to replace double quotes for the texts only but not for the tag attributes. So my output should be as below.
var myoutput = '<p class="abc">some text here</p><p class="xyz"><img src="img.jpg" title="my img"/> some "double quoted text" here</p>'
Can you suggest me a solution please. Thank you!

Try this:
function replace_text(node){
node = node || document.getElementById('mydiv'); // Change 'mydiv' if you need
var children = node.childNodes;
var i = 0;
while(node = children[i]){ // While-loop
if (node.nodeType == 3){ // Some text, replace
if (node.textContent) { // Not IE (IE's equivalent to textContent is nodeValue)
node.textContent = node.textContent.replace(/"/g, '"');
}
else { // IE
node.nodeValue = node.nodeValue.replace(/"/g, '"');
}
} else { // not text, take step further
replace_text(node);
}
i++;
}
} // While-loop
// Don't forget to call function
replace_text();

With Jquery You can do this :
String.prototype.replaceAll = function(stringToFind,stringToReplace){
var temp = this;
var index = temp.indexOf(stringToFind);
while(index != -1){
temp = temp.replace(stringToFind,stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
};
$(function(){
$("#mydiv").children().each(function(){
var text=$(this).text();
text=text.replaceAll("\"",""");
//alert(text);
$(this).text(text);
});
});

Related

Simple formatting in textarea

I am trying to make a blog type of website. I got to a point where you can enter text into a textarea box and then click submit to have it appear below. However, I have come to a problem where it does not save the format of the input (notably for me, transforms paragraphs into spaces). I have read that this would require a rich-text editor, and I have tried TinyMCE but it gives a lot more options than needed or which would be able to be used in my case. Is there a simple way to fix this problem? If not, what is the best way to go about this?
I am mainly after the paragraph, tab, and multiple spaces formatting, everything else is currently not needed.
Here is what I currently have that is related:
HTML
<!-- Blog Section -->
<div class="itemBlog">
<h2 id="itemBlogTitle">My Blog</h2>
<textarea type="text" rows="10" cols="100" class="blogTextArea" id="blogInput"></textarea>
<div onclick="newBlog()" class="addBtn">Add</div>
<ul id="blogList"></ul>
</div>
<script src="itemblog.js"></script>
JavaScript
// Create a new blog item when clicking on the "Add" button
function newBlog() {
var li = document.createElement("li");
var inputValue = document.getElementById("blogInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue != '') {
document.getElementById("blogList").appendChild(li);
}
document.getElementById("blogInput").value = "";
var textarea = document.createElement("TEXTAREA");
var txt = document.createTextNode("\u00D7");
textarea.className = "close";
textarea.appendChild(txt);
li.appendChild(textarea);
for (i = 0; i < close.length; i++) {
close[i].onclick = function () {
var div = this.parentElement;
div.style.display = "none";
}
}
}
EDIT: white-space: pre-wrap; fixed it, thank you
If you want something simple, just save into your database the input content with id description, after that it will respect the paragraph and spaces.
JQUERY
$('#test').keyup(function() {
var text = $(this).val();
var description = text.replace(/ /g, ' ').replace(/[\n]/g, '<br>');
$('#text').html(description)
$('#description').val(description)
});
<textarea id="test" cols="30" rows="10"></textarea>
<input id="description" name="description" hidden>
<div id="text"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
js
function formatString(el) {
var str = el.value;
str = str.replace(/ /g, ' ').replace(/[\n]/g, '<br>');
document.getElementById('text').innerHTML = str;
document.getElementById('description').value = str;
}
<textarea onkeyup="formatString(this)" cols="30" rows="10"></textarea>
<input id="description" name="description" hidden>
<div id="text"></div>
You can create a function nl2br() as folows:
function nl2br (str, is_xhtml) {
if (typeof str === 'undefined' || str === null) {
return '';
}
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');
}
You can see more here

Find lines in an element and then wrap it with <span> tags

I need to write a code where I split the html by br, find lines that start with a number and then add in span tags.
jQuery(document).ready(function($) {
var brExp = /<br\s*\/?>/i;
var swn = /^[0-9]+[^)]/;
var lines = $('.caption').html().split(brExp).filter(line => swn.test(line.trim()));;
jQuery.each(lines, function() {
console.log(this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="caption">
BBQ Porked Rolls.
Ingredients:
3 to 4 pounds pork shoulder<br />
1 tablespoon salt<br />
2 tablespoons brown sugar<br />
STEPS:
In the oven,...
<div>
I’ve already gotten the lines and all that’s left is to add in span tags around those lines without the need to create a new div for the result. Maybe by using replace(), wrap() or something else entirely. This is where I need help.
EXPECTED OUTPUT:
<span itemprop="recipeIngredient">3 to 4 pounds pork shoulder</span><br>
<span itemprop="recipeIngredient">1 tablespoon salt</span><br>
<span itemprop="recipeIngredient">2 tablespoons brown sugar</span><br>
Thanks
You just need to map() over the collection.
jQuery(document).ready(function($) {
var brExp = /<br\s*\/?>/i;
var swn = /^\d/;
var lines = $('.caption').html().split(brExp).map(function (line) {
// strip the whitespace
line = line.trim();
// check for number
if ( swn.test(line) ) {
// add enclosing span
line = '<span itemprop="recipeIngredient">' + line + '</span>';
}
// return the line for the new collection
return line;
}).join('<br />');
$('.caption').html(lines);
});
If you only want to change the first line, you can make the following minor change to the code:
jQuery(document).ready(function($) {
var firstOnly = true; // will check for number when this value is true
var brExp = /<br\s*\/?>/i;
var swn = /^\d/;
var lines = $('.caption').html().split(brExp).map(function (line) {
// strip the whitespace
line = line.trim();
// check 'firstOnly' is true before checking for number
if ( firstOnly && swn.test(line) ) {
// add enclosing span
line = '<span itemprop="recipeIngredient">' + line + '</span>';
// first matching line has been modified
// so set 'firstOnly' to false
firstOnly = false;
}
// return the line for the new collection
return line;
}).join('<br />');
$('.caption').html(lines);
});
Another approach could be using .replace() as you said.
jQuery(document).ready(function($)
{
var text = $(".caption").html();
var newText = text.replace( /(\d+.+)(<br)/g, '<span itemprop="recipeIngredient">$1</span>$2');
console.log(newText);
$(".caption").html(text);
});
the regex must be fixed a little, but i think the approach is valid.
https://jsfiddle.net/g6yegh1f/
UPDATE
You can try this :
jQuery(document).ready(function($)
{
var html = '';
var brExp = /<br\s*\/?>/i;
var lines = $('.caption').html().split(brExp);
jQuery.each(lines, function(index, value) {
html += '<span>' + value + '</span></br>';
});
$('.caption').html(html);
});
Use this link which has the number check and then appending the data to span taghttps://codepen.io/anon/pen/ZoaXYR?editors=1010
var data = `3 to 4 pounds pork shoulder<br />1 tablespoon salt<br />2 tablespoons brown sugar<br />`;
var brExp = /<br\s*\/?>/i;
var swn = /^\d/;
var lines = data.split(brExp).filter(line => swn.test(line.trim()));
$.each(lines, function() {
var ff = Number(this[0]);
alert(typeof(ff));
if(typeof(ff) == "number") {
alert("success");
$("#first").append("<span id='test'>" +this+"</span>");
}
});
I would probably do this:
jQuery(document).ready(function($) {
var brExp = /<br\s*\/?>/i;
var swn = /^\d/;
var lines = $('.caption').html().split(brExp)
//create span
lines= lines.map( line =>$('<span />').prop('itemprop','recipeIngredient').html(line))//.join('<br />');
//empty the div
$('.caption').empty();
jQuery.each(lines, function() {
$('.caption').append(this);
$('.caption').append('<br />');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="caption">
3 to 4 pounds pork shoulder<br />
1 tablespoon salt<br />
2 tablespoons brown sugar<br />
<div>
You can use the index to find the value that corresponds to the 0 key, check if it is a number and then use append/before methods to bind the same.

jQuery - How to wrap each character from a string in spans

How can I convert the characters of a div into spans?
For example, I'd like to convert this:
<div>
Hello World
</div>
Into this:
<div>
<span>H</span>
<span>e</span>
<span>l</span>
<span>l</span>
<span>o</span>
<span>W</span>
<span>o</span>
<span>r</span>
<span>l</span>
<span>d</span>
</div>
I've tried this StackOverflow suggestion, but that converts spaces into spans. What I need is to convert only characters to spans:
$("div").each(function (index) {
var characters = $(this).text().split("");
$this = $(this);
$this.empty();
$.each(characters, function (i, el) {
$this.append("<span>" + el + "</span");
});
});
You can use String#replace method and html() method with a callback to reduce the code.
$("div").html(function(index, html) {
return html.replace(/\S/g, '<span>$&</span>');
});
$("div").html(function(index, html) {
return html.replace(/\S/g, '<span>$&</span>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Hello World
</div>
You can try with this simple JavaScript.
(function() {
var div, i, span = "";
div = document.querySelectorAll("div")[0];
for (i = 0; i < div.innerText.length; i++) {
if (div.innerText[i] !== " ") {
span += "<span>";
span += div.innerText[i];
span += "</span>";
}
}
div.innerHTML = span;
}());
<div>
Hello World
</div>
I'd prefer to use regular expression:
var txt = $('#container').text();
var newTxt = txt.replace(/\w/g,function(c){
return '<span>'+c+'</span>';
})
$('#container').html(newTxt);
span {
display:inline-block;
background-color:#dfdfdf;
color:#aaa;
padding:3px;
margin:3px;
border-radius:3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
Hello World
</div>
var textWrapper = document.querySelector('h1');
textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");
<h1>Hello world</h1>
$("div").each(function (index) {
var characters = $(this).text().split("");
$this = $(this);
$this.empty();
$.each(characters, function (i, el) {
if(el != ' ')
$this.append("<span>" + el + "</span");
});
put a condition for space
try:
$("div").each(function (index) {
var characters = $(this).text().split("");
characters = characters.filter(v => v != '');
$(this).empty();
for(var i =0; i < characters.length; i++) {
$(this).append("<span>" + characters[i] + "</span");
}
});
tried to write as little as I can
html
<div>
HelloWorld
</div>
js
var d=$("div");
var text=d.text();
text=$.trim(text);
d.empty();
for(i=0;i<text.length;i++){
var span=$("<span></span>");
span.text(text[i]);
d.append(span)
}

Find matched letter from each word in javascript array

I have an array in javascript like that :
var books = ['spring','last night','sweet heart','the sky','tomorrow'] ;
I have textarea
<textarea id="text" name="textpreview" class="text"></textarea>
So what I want is when I enter letter s then I will get two suggestions books just the first word not the second word I mean not sky Just spring and sweet heart .
I will get two spans
<textarea id="text" name="textpreview" class="text"></textarea>
<span>spring</span>
<span>sweet heart</span>
If I type again after s the p letter like sp in textarea then I will get just spring
<textarea id="text" name="textpreview" class="text"></textarea>
<span>spring</span>
and so on .
If I type n I will get nothing.
If I type t I will get tomorrow and the sky
Hope it can be done . Thanks for your support .
This help you :
<html>
<head>
<title></title>
</head>
<body>
<textarea id="text" name="textpreview" class="text"></textarea>
<p id="x"></p>
<script>
var x = document.getElementById("x");
var books = ['spring','last night','sweet heart','last night','the sky','tomorrow','tomorrow'];
var txt = document.getElementById("text");
txt.onkeyup = function(event) {
var str = "";
var arr = [];
var index = (txt.value).indexOf("#");
if(index !== -1 && (txt.value).substr(index + 1).length > 0) {
var value = (txt.value).substr(index + 1);
value = value.replace(/[\.\+\*\\\?]/g,'\\$&');
var patt = new RegExp("^" + value);
for(var i=0; i<books.length; i++) {
if(patt.test(books[i]) && arr.indexOf(books[i]) === -1) {
arr.push(books[i]);
}
}
}
if (arr.length < 1 )
x.innerHTML = "";
else {
for(var i=0; i<arr.length; i++)
str+=arr[i]+"<br>";
x.innerHTML = str;
}
}
</script>
</body>
</html>
This problem consists of two parts: Reading and writing your input/output from/to the DOM, and filtering your array books.
The reading and writing part should be easy, there are plenty of guides on how to achieve this.
To filter the books array, JavaScript offers a number of helpful functions:
var books = ['spring','last night','sweet heart','the sky','tomorrow'];
var input = 'S';
var result = books.filter(function(book) {
return book.toLowerCase().indexOf(input.toLowerCase()) === 0;
}).slice(0, 2);
console.log(result); // ['spring', 'sweet heart']
#TimoSta is correct that this is a two-part problem.
I expanded on his code a bit using angular to display the results in the DOM.
http://jsfiddle.net/kcmg9cae/
HTML:
<div ng-controller="MyCtrl">
<textarea id="text" name="textpreview" class="text" ng-model="startsWith"></textarea>
<span ng-repeat="book in sortedBooks()">{{ book }}</span>
</div>
Javascript:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.books = ['spring','last night','sweet heart','the sky','tomorrow'];
$scope.sortedBooks = function () {
var sortedBooks = [];
for (var i = 0; i < $scope.books.length; i++){
if ($scope.books[i].toLowerCase().indexOf($scope.startsWith.toLowerCase()) === 0)
sortedBooks.push($scope.books[i]);
}
return sortedBooks;
}
}

Check if value is a whitespace

I'm trying to write something like an image font generator, but I can not check if the form value is an space, or give an URL to an whitespace image.
Here is my code:
<html><head><title>untitled</title>
<script type="text/javascript">
<!--
function fontgen(text) {
var url = './fonts/';
var letters = text.split('');
var imgStr = "";
for (var i in letters) {
imgStr += '<img src="' +url+letters[i]+ '.gif">';
}
document.getElementById('name').innerHTML = imgStr;
return false;
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<input type="text" name="myinput" size="20"><br>
<input type="button" value="Make Font" onclick="return fontgen(document.myform.myinput.value)">
</form>
<div id="name"></div>
</body>
</html>
function fontgen(text) {
var url = './fonts/',
letters = text.split(''),
imgStr = "";
// First, you need a valid for loop:
for (var i = 0; i < letters.length; i++) {
if (letters[i] !== ' ') { // then, check to see if it is a space
imgStr += '<img src="' +url+letters[i]+ '.gif">';
}
}
document.getElementById('name').innerHTML = imgStr;
return false;
}
From what I can tell from your question, you're looking for something like this:
for (var i=0;i<text.length;i++)
{
if (text.charAt(i) !== ' ')
{//using charAt, you're supporting all browsers, without having to split the string
console.log(text.charAt(i) + ' is not space');
}
}
But an easier way of doing this, without having to loop through all chars, 1 by 1, is this:
if (text.indexOf(' ') === -1)
{
console.log('No spaces in ' + text + ' found');
}
Or, if you want to, you can replace or remove all spaces in one go:
text = text.replace(/\s/g,'_');//replaces spaces with underscores
text = text.replace(/\s/g, '');//removes spaces
Regex-mania way. Suppose you have a certain set of chars as gifs, you can easily use a single regex to replace all of those chars with their corresponding images in one fell swoop:
var imgString = text.replace(/([a-z0-9\s])/gi, function(char)
{
if (char === ' ')
{
char = 'space';//name of space img
}
return '<img src="'url + char + '.gif"/>';
});
Same logic applies to chars like ! or ., since they're not exactly suitable for file names, use an object, array or switch to replace them with their corresponding file-names.Anyway, with input like foo bar, the output of the code above should look something like this:
<img src="./fonts/f.gif"/><img src="./fonts/o.gif"/><img src="./fonts/o.gif"/><img src="./fonts/space.gif"/><img src="./fonts/b.gif"/><img src="./fonts/a.gif"/><img src="./fonts/r.gif"/>
Not sure why your path is ./foo/[].gif, I suspect foo/[].gif would do just as well, but that's not the issue at hand here.
In case you're interested: here's some more about replacing using regex's and callbacks
try replacing letters[i]
with:
(letters[i] == " ") ? "spacefilename" : letters[i]
this is a ternary operator. basically a shorthand if statement that can be used directly in place of letters[i]
in a sense it would be like replacing letters[i] with myfilename(letters[i])
where the myfilename function is
function myfilename(char)
{
if (char == " ") {
return "space";
} else {
return char;
}
}
so your code would look like this:
<html><head><title>untitled</title>
<script type="text/javascript">
<!--
function fontgen(text) {
var url = './fonts/';
var letters = text.split('');
var imgStr = "";
for (var i = 0; i < letters.length; i++) {
imgStr += '<img src="' +url+(letters[i] == " ") ? "spacefilename" : letters[i]+ '.gif">';
}
document.getElementById('name').innerHTML = imgStr;
return false;
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<input type="text" name="myinput" size="20"><br>
<input type="button" value="Make Font" onclick="return fontgen(document.myform.myinput.value)">
</form>
<div id="name"></div>
</body>
</html>
/e also as someone else mentioned, the for loop is wrong. i corrected that just now.
a "for...in" loop could work there... don't want to get into all that though.
Try changing the character into a char code and having a corresponding image file for each code you want to support; you can also put a range check via if statement to make sure the codes fall within your accepted ranges.
function fontgen(text)
{
var imgStr = "";
for (var i = 0; i < text.length; i++)
imgStr += '<img src="./fonts/' + text[i].charCodeAt(0) + '.gif">';
document.getElementById('name').innerHTML = imgStr;
return false;
}
If you supply this function the phrase "this is a test" it will result in:
<div id="name">
<img src="./fonts/116.gif">
<img src="./fonts/104.gif">
<img src="./fonts/105.gif">
<img src="./fonts/115.gif">
<img src="./fonts/32.gif">
<img src="./fonts/105.gif">
<img src="./fonts/115.gif">
<img src="./fonts/32.gif">
<img src="./fonts/97.gif">
<img src="./fonts/32.gif">
<img src="./fonts/116.gif">
<img src="./fonts/101.gif">
<img src="./fonts/115.gif">
<img src="./fonts/116.gif">
</div>
<img src="./fonts/32.gif"> would be the space image.

Categories