On my page I have a text area. Inside is some characters.
I need these removed.
I know I can use replace to do this but when I access the .html() of the text area they do not appear.
console.log($('#my-textarea').html());
So doing a replace on the above has to effect.
How can I remove these characters?
Edit:
$('#my-textarea').html().replace(/\/g,'');
The above fails to remove the hidden chars.
replace(//g, '') didn't work because HTML and javascript use different encodings to represent special characters.
You could use unicode representation to remove this special character.
$('#replace').click(function() {
var $text = $('#my-textarea');
console.log($text.html())
$text.html($text.html().replace(/\u200C/g, '?')); // ? for demo
console.log($text.html())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my-textarea">
test test
test test
test test
test test
test test
</div>
<button id="replace">Replace</button>
If you don't require html as a value for something, this might do the trick:
console.log( $('#my-textarea').text() );
The jQuery .text() method does a nice job of sanitizing the input, it returns text, only, and strips the rest away.
Related
I have an html page where some words are split by so they look e.g. like FRigVMExternalVariable but in the code they are actually FRigVMExternalVariable. And the problem is that when I click the word it selects only a part that is bordered by while the desirable behavior is for it to select the whole word
How to override default double click behavior in JS so it would treat not as a word boundary?
You can triple-click to select the entire line/paragraph. Otherwise, is a word separator as explained in this question, so the default browser action on double click is to select the word under the cursor.
<!DOCTYPE html>
<html lang='pt-br'>
<head>
<title>Teste</title>
</head>
<body>
abettertest with spaces<br>
abettertest with spaces<br>
</body>
</html>
I found a solution which preserves the ability for a word to be soft-broken at specific positions but doesn't interfere with selection. It's tag </wbr>. When I replace on </wbr> the word can be soft broken at the </wbr>s but when I click any part of a word the whole word gets selected.
F<wbr/>Rig<wbr/>V<wbr/>M<wbr/>External<wbr/>Variable<wbr/>
If you don't need zero width spaces, you should just remove them using .replace() and the regex flag \u which enables Regex methods to recognize Unicode. The Unicode for a zero width space is: U+200B which in the land of JavaScript is: \u200B.
function noZero(string) {
return string.replace(/\u200B/gu, '');
}
const str = document.querySelector(".zero").innerHTML;
const result = noZero(str);
document.querySelector(".clean").insertAdjacentHTML("beforeend", result);
<p class="zero">Try <u>selecting</u> the underlined word.</p>
<p class="clean"></p>
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+$/.
I want to remove HTML DOM object by its ID, that contains special characters(dots, commas etc). I tried to use this code that escapes those characters but it's not working (element its not being removed):
var file_html_id ="#"+ filename.replace(/[!"#$%&'()*+,.\/:;<=>?#\[\\\]^`{|}~]/g, "\\\\$&");
console.log(file_html_id);
$(file_html_id).remove();
where filename its the ID. It's worth to mention that string with escaped characters is displayed as expected. And if I "hardcode" that string it works fine... So where the problem might be?
Instead of trying to escape the characters yourself you could try a couple of other ways:
Use jQuery's escapeSelector() on the id string. This will escape any special characters in the string. Note escapeSelector was added in v3.0 of jQuery. View how they are doing the escaping here
if interested.
$( '#'+ $.escapeSelector('theText') )
Use an attribute selector instead of trying to escape all the possible characters for an id selector
$('[id="idHere"]')
This however will select multiple elements if for some bizarre reason you have multiple elements with the same id.
Demo
var id = "some,weird®,id";
var id2 = "some,other®,id";
$('#'+ $.escapeSelector(id2) ).css({border:'1px solid green'});
$('[id="'+id+'"]').css({border:'1px solid red'});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div id="some,weird®,id"></div>
<br/>
<div id="some,other®,id"></div>
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 am using a markdown parser that works great if I pass it a string like this:
el.innerHTML = marked('#Introduction:\nHere you can write some text.');
But if I have that string inside HTML and send it to parser like
el.innerHTML = marked(otherEl.innerHTML);
it does not get parsed. Why is this? Does the string format of .innerHTML do something I am missing?
jsFiddle: http://jsfiddle.net/5p8be1b4/
My HTML:
<div id="editor">
<div class="contentTarget"></div>
<div class="contentSource">#Introduction:\nHere you can write some text.</div>
</div>
div.contentTarget should receive HTML, parsed markdown. But it receives a un-parsed string only.
In the image bellow is the jsFiddle output. A unformated div.contentTarget, the original div.contentSource where I get the innerHTML to use in div.contentTarget and in the bottom, a working parsed div#tester which received a string directly into the parser.
The issue is around your newlines. When you put \n inside a string in javascript, you're putting an actual newline character in it.
The same \n inside your HTML content is just that, \n. It is not a newline. If you change your HTML to this (with an actual newline), it works as expected:
<div class="contentSource">#Introduction:
Here you can write some text.</div>
Updated fiddle
Alternatively, if you change your javascript string to:
test.innerHTML = marked('#Introduction:\\nHere you can write some text.');
So that the string actually contains \n rather than a newline, you see the same erroneous behaviour.
Got it.
In your html, you have \n, but it's supposed to be a line-break, and you should use br becasue this is supposed to be html.
<div class="contentSource">#Introduction:<br/>Here you can write some text.</div>
instead of:
<div class="contentSource">#Introduction:\nHere you can write some text.</div>
When you debug the code, if you send the innerHTML to marked, it shows this as a function parameter:
#Introduction:\nHere you can write some text.
But when you send the string in the js, it shows the parameter like this:
#Introduction:
Here you can write some text.
Hope this helps.
JsFiddle: http://jsfiddle.net/gbrkj901/11/
Your HTML is rendering differently because Javascript automatically interprets \n as a newline.
Consider the following:
alert('a\ntest');
Which will have an alert with 2 lines.
And now, consider the following:
<span>a\ntest</span>
<script>
alert(document.getElementsByTagName('span')[0].innerHTML);
</script>
This will show a\ntest.
To fix it, use this:
el.innerHTML = marked(otherEl.innerHTML.replace(/\\n/g,'\n'));
Or, a more general and secure way:
el.innerHTML = marked(
otherEl
.innerHTML
.replace(
/\\([btnvfr"'\\])/g,
function(_,c){
return {
b:'\b',
t:'\t',
v:'\v',
n:'\n',
r:'\r',
'"':'"',
"'":"'",
'\\':'\\'
}[c];
}
)
);
Or, if you like it minimal and you are ready to have cthulhu knocking on your front door, use this:
el.innerHTML = marked(otherEl.innerHTML.replace(/\\([btnvfr])/g,function(_,c){return eval('return "\\'+c+'"');}));