I am trying to validate if the contenteditiable value has only whitespace/blank space. In my example if the value have only whitespace/blank space it should not match according to my regex string, but it not working as intended. It keeps matching when I enter complete blank spaces.
edit: the black space is where you can enter text.
https://jsfiddle.net/j1kcer26/5/
JS
var checkTitle = function() {
var titleinput = document.getElementById("artwork-title").innerHTML;
var titleRegexp = new RegExp("^(?!\s*$).+"); //no blank spaces allowed
if (!titleRegexp.test(titleinput)) {
$('.start').removeClass('active-upload-btn');
console.log('no match')
} else if (titleRegexp.test(titleinput)) {
$('.start').addClass('active-upload-btn');
console.log('match')
}
};
$('#artwork-title').on('keyup change input', function() {
checkTitle();
});
HTML
<div class="post-title-header">
<span class="user-title-input title-contenteditable maxlength-contenteditable" placeholder="enter text here" contenteditable="true" name="artwork-title" id="artwork-title" autocomplete="off" type="text" spellcheck="false">
</span>
</div>
<div class="start">
turn red if match
</div>
If you look at the actual inner HTML, you'll see things like <br> elements or entities. Your regex doesn't look equipped to handle these.
You may want to consider using textContent instead of innerHTML if you just care about the text, not the HTML. Or alternatively, if you really want plain text, use a <textarea/> instead of a content-editable div, which is for rich-text-style editing that produces HTML.
Edit:
Your regex is not quite right either. Because you're using the RegExp constructor with new RegExp("^(?!\s*$).+"), the \s in your string literal is going to turn into a plain s; you have to use a \\s if you want the regex to have an actual \s in it. IMO, it's always better to use a regexp literal unless you're building one dynamically, like /^(?!\s*$).+/, or I find this to be a simpler alternative to tell you if a string is entirely whitespace: /^\s+$/.
Related
The property is like this.
key: "paragraph.\n More text.\n Another sentence."
How would I show it like...
paragraph.
More text.
Another sentence.
without iterating or split()ting the text?
Number of paragraphs will be unknown at time of read. I have access to the object to rewrite the text in some other format, but it needs to stay as a single property.
I've tried
<p>{item["instruction"]}</p>
<p>{item.instruction}</p>
which both return solid blocks.
You can use for example css 'white-space':
<p style="white-space: pre-line;">{item.instruction}</p>
Or depending on what template library you use replace \n sign with <br /> tag (but most template libs escape html when rendering the value).
you can replace all \n in your string with <br /> element
for replace all \n in your string you must use RegExp in replace method.
var key = "paragraph.\n More text.\n Another sentence."
// put result of this command in your html element
key.replace(/\n/g,'<br />')
I am trying to remove empty all paragraph tags, regardless of what style attributes might be in the p tag, from a string. I want to remove, for example, all of these and replace with an empty string.
<p style="margin-left:0px"></p>
<p></p>
<p style="margin-left:1cm; margin-right:1cm"></p>
So far, to deal with one situation I have, I am doing this:
str = str.replace(/<p style=\"margin:0cm 0cm 10pt\"><\/p>/g,'')
which is working in that particular situation. How can I write it so it removes
<p AnythingHereInThisTag></p>
and replaces it with an empty string?
Edit - further to answer below - if I do this:
str = str.replace(/<p(.*)><\/p>/g,'')
it is replacing the whole string which might look like
<p>Hello</p><p>Some text in the middle</p><p>Goodbye</p>
It needs to look at each pair of tags
Replace Any charecter without a char " has the regex as [^\"]
var reg=/\<p( [a-zA-Z]*=((\"[^\"]*\")|(\'[^\']*\')))*\>\<\/p\>/g;
console.log('<p style=\'margin:0cm 0cm 10pt\'></p>'.replace(reg,''));
console.log('<p style=\"margin:0cm 0cm 10pt\"></p>'.replace(reg,''));
console.log('<p style=\"margin:0cm 0cm 10pt\" class=\"test\"></p>'.replace(reg,''));
console.log('<p></p>'.replace(reg,''));
Something like this?
str = 'asd<p style="margin-left:0px"></p><p></p><p style="margin-left:1cm; margin-right:1cm"></p>'
str.replace(/<p(.*)><\/p>/g,'') // "asd"
Reading the question again, it is unclear if you wanted to remove only the attributes within the tag, or the tag completely. Please clarify.
You can read more about regular expression here.
I have an html element and i toggle its class and show capital/small letters with text-transform.
Is it possible to get the text its text-transform?
$('#toggle').click(function(){
$('#char').toggleClass('upper');
});
$('#getdata').click(function(){
var text = $('#char').text();
alert(text); /// here i need to get the actual word with capital/lower i selected
});
.upper{
text-transform:uppercase;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span contenteditable="true" id="char">a</span>
<br/>
<button id="toggle">Toggle case</button>
<button id="getdata">gat data</button>
you can check for the class and use toUpperCase:-
$('#toggle').click(function(){
$('#char').toggleClass('upper');
});
$('#getdata').click(function(){
var $char = $('#char');
var text = $char.hasClass('upper') ? $char.text().toUpperCase() : $char.text();
alert(text); /// here i need to get the actual word with capital/lower i selected
});
.upper{
text-transform:uppercase;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span contenteditable="true" id="char">a</span>
<br/>
<button id="toggle">Toggle case</button>
<button id="getdata">gat data</button>
There is currently no way to get the rendered text with JavaScript.
When you are using English, toUpperCase and toLowerCase works well for the CSS value uppercase and lowercase.
But when you need it for non-English, or when you use capitalize, full-width etc., you have to reproduce the CSS logic (mostly unicode logic) with JS.
Below is a few rules that Firefox is doing. Chrome also knows some of them.
In German (de), the ß becomes SS in uppercase.
In Dutch (nl), the ij digraph becomes IJ, even with text-transform: capitalize, which only put the first letter of a word in uppercase.
In Greek (el), vowels lose their accent when the whole word is in uppercase (ά/Α), except for the disjunctive eta (ή/Ή). Also, diphthongs with an accent on the first vowel lose the accent and gain a diaeresis on the second vowel (άι/ΑΪ).
And so on...
It's also fun when you need to apply other CSS values:
capitalize - What constitutes a "word"? How do browsers split iPhone-6s+? Behold, Unicode consortium to the rescue!
full-width - The MDN example looks easy, but it does not show them all, for example [] to [], and maybe someday they will convert ... to … instead of ...
full-size-kana - How's your Japanese? No worry, this CSS4 proposals is dropped - in preference of a (future) fully customisable character mapping rules! Hope your CSS parser skill is up to par.
So, count yourself lucky if you use only English. You have my consolation if you, like me, work with multilingual systems. Timezone is nothing at all.
Maybe like this?
// Store css to javascript values in this object
var textTypes = {
"uppercase": "toUpperCase",
"lowercase": "toLowerCase"
}
// get the element
var div = document.getElementsByTagName('div')[0];
// get the computed style type
var type = window.getComputedStyle(div)['text-transform'];
// print the transformed text
console.log(div.innerHTML[textTypes[type]]());
Working Fiddle
I have several string in the following format
<span class="label">20€</span>
And want to convert it all to something like this:
<span class="label">20<small>€</small></span>
How could I achieve this in Jquery?
I'd suggest:
$('.label').html(function(i,h){
return h.replace(/([^\d+])/,'<span class="small">$1</span>');
});
JS Fiddle demo.
Bearing in mind that I'm choosing to use span with a class of small, rather than a small element.
Under HTML 5, though, remember that the small element is:
repurposed to represent side-comments and small print, including copyright and legal text, independent of its styled presentation.
Source: https://developer.mozilla.org/en-US/docs/HTML/Element/small.
If the currency symbol is predictable, you could explicitly replace the € character (rather than using the above to replace, essentially, 'not-numbers'):
$('.label').html(function(i,h){
return h.replace(/(€)/,'<span class="small">$1</span>');
});
JS Fiddle demo.
Or, assuming the currency symbols are known in advance, you could specify the symbols to be replaced (using regular expressions again, though):
$('.label').html(function(i,h){
return h.replace(/([€£$])/,'<span class="small">$1</span>');
});
JS Fiddle demo.
References:
html().
Regular expressions.
String.replace().
It works, but is affecting other strings that doesn't have the €
character. I mean other spans with the same class, it changes the
first letter or those strings. Figure I have other strings with this
syntax: <span class="label">request price</span>
HTML:
<span class="label currency">20€</span>
Note 1: Added additional class currency to identify the span that needs to be modified.
Note 2: Use a span instead of small as all styles elements are re purposed. (Thanks #David). Read more info #MDN https://developer.mozilla.org/en-US/docs/HTML/Element/small
You can use replace function like below,
$(function () {
$('span.label.currency').html(function(i, v) {
return v.replace('€', '<small>€</small>');
});
});
I have the HTML from a page in a variable as just plain text. Now I need to remove some parts of the text. This is a part of the HTML that I need to change:
<div class="post"><a name="6188729"></a>
<div class="igmline small" style="height: 20px; padding-top: 1px;">
<span class="postheader_left">
RuneRifle
op 24.08.2012 om 21:41 uur
</span>
<span class="postheader_right">
Citaat Bewerken
</span>
<div style="clear:both;"></div>
</div>
<div class="text">Testforum</div>
<!-- Begin Thank -->
<!-- Thank End -->
</div>
These replaces work:
pageData = pageData.replace(/href=\".*?\"/g, "href=\"#\"");
pageData = pageData.replace(/target=\".*?\"/g, "");
But this replace does not work at all:
pageData = pageData.replace(
/<span class=\"postheader_right\">(.*?)<\/span>/g, "");
I need to remove every span with the class postheader_right and everything in it, but it just doesn't work. My knowledge of regex isn't that great so I'd appreciate if you would tell me how you came to your answer and a small explanation of how it works.
The dot doesn't match newlines. Use [\s\S] instead of the dot as it will match all whitespace characters or non-whitespace characters (i.e., anything).
As Mike Samuel says regular expressions are not really the best way to go given the complexity allowed in HTML (e.g., if say there is a line break after <a), especially if you have to look for attributes which may occur in different orders, but that's the way you can do it to match the case in your example HTML.
I need to remove every span with the class postheader_right and everything in it, but it just doesn't work.
Don't use regular expressions to find the spans. Using regular expressions to parse HTML: why not?
var allSpans = document.getElementsByClassName('span');
for (var i = allSpans.length; --i >= 0;) {
var span = allSpans[i];
if (/\bpostheader_right\b/.test(span.className)) {
span.parentNode.removeChild(span);
}
}
should do it.
If you only need to work on newer browsers then getElementsByClassName makes it even easier:
Find all div elements that have a class of 'test'
var tests = Array.filter( document.getElementsByClassName('test'), function(elem){
return elem.nodeName == 'DIV';
});