Removing HTML elements with special characters - javascript

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>

Related

jQuery selector for data attribute array

Theres' this html code:
<div class="wcpa_form_outer" data-attrrelated="["wcpa-select-1658734650073"]">
for which i'm trying to append html to it. I have tried various approaches but none have worked.
jQuery('.wcpa_form_outer[data-attrrelated="["wcpa-select-1658734650073"]"]').append('some html here');
or
jQuery('.wcpa_form_outer[data-attrrelated="[wcpa-select-1658734650073]"]').append('some html here');
or
jQuery('.wcpa_form_outer').data('attrrelated').append('some html here');
any clues?
The " and/or [] in the attribute value may be the problem Remove it, or try using a part (the most relevant part?) of the attribute value:
$('[data-attrrelated*="1658734650073"]')
.append('some html here!');
$('[data-attrrelated*="wcpa-select-165873465007"')
.append('<br>some html here too!');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wcpa_form_outer" data-attrrelated="["wcpa-select-1658734650073"]"></div>
Problem is that you're using the HTML Entity " in your attribute. This is being translated to a literal quote. JQuery does not do Entity translation, so it's literally looking for the string ["wcpa-select-1658734650073"] with ampersands and all, not ["wcpa-select-1658734650073"] which is the actual value in your attribute.
You can work around this by using one of the following methods (after also translating the Entity into a quote in your code).
Use a CSS "contains" selector for your attribute ( attr*=value ) (demonstrated by KooiInc's answer) or
Use a string template which will allow you to embed both types of quotes in your string and get an exact match ( attr=value ), shown below
Constructing a string value containing quotes by using string concatenation (e.g. '["' + value + '"]' )
Use the decodeEntities function from this answer to translate your attribute value before attempting the lookup (untested, and it's 10 years old)
jQuery(`.wcpa_form_outer[data-attrrelated='["wcpa-select-1658734650073"]']`).append('foo')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wcpa_form_outer" data-attrrelated="["wcpa-select-1658734650073"]">append here:
</div>

Contenteditable regex whitespace not working

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+$/.

Remove ‌ characters

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.

I have a problem with slash in javaScript n Ajax

I have a problem with slash in javaScript n Ajax
I am displaying value dynamically in a span like below:
String num = "37-C110PDD/L";
<span id="p21stk_<%=NUM%>"></span>
in Script:
value for chks[0] is 37-C110PDD/L here the value contains slash and is not displaying the required value in span
Code used in script to update value dynamically:
$("#p21stkArwhed_"+chks[0].value).html($("#qohArrVal_"+chks[0].value).val())
Above code working for parameters without SLASH
Any idea how to solve....?
Thank you..........
Using slashes in the attribute ID is illegal.
See What are valid values for the id attribute in HTML?
You should replace your slash with a valid character, an hyphen ("-") or an underscore ("_") for example.
You can use custom data-* attributes (http://www.w3.org/TR/html5/elements.html#embedding-custom-non-visible-data-with-the-data-attributes), for example:
HTML:
<span data-id="37-C110PDD/L">a span</span>
JS:
alert( $("span[data-id='37-C110PDD/L']").text() );

javascript replace issue

i have buildt a small highlight script, this script has a results tags, which means that you can enter words in a input field and it will be displayed as clickable tags, the tags are created by a whitespace(enter space and a new tag will form). You can click on the tags to remove the results from the input and text.
The issue, if you enter a single letter and click it to remove it, it removes all letters in all of the search words(so click on a single a all of the a's are beeing removed from the search input)
the code
$('a').live('click',function(){
var searchPhrase = $(this).text();
$('input').val(
$('input').val().replace(searchPhrase,'')
);
})
i use this piece of code to simple remove the matched text from the input.
What do i need, well the tags should be removed if they match, so i need to include a regex begin of a string pattern....i think.
Found the solution:
var reg = new RegExp("\\b"+ searchPhrase +"\\b", "g");
Use: Regular Expressions for JavaScript, instead of JavaScript plain search method.

Categories