JQuery - Slice/Remove - Special characters from ID or class name The 2019 Stack Overflow Developer Survey Results Are InJavascript regex to remove illegal characters from DOM IDWhat is the best way to add options to a select from as a JS object with jQuery?Best way to remove an event handler in jQuery?How to remove close button on the jQuery UI dialog?How can I select an element with multiple classes in jQuery?How can I select an element by name with jQuery?How to remove all CSS classes using jQuery/JavaScript?Removing multiple classes (jQuery)Get selected text from a drop-down list (select box) using jQueryGet class name using jQueryjQuery Get Selected Option From Dropdown

What is this business jet?

How can I define good in a religion that claims no moral authority?

Is it ethical to upload a automatically generated paper to a non peer-reviewed site as part of a larger research?

What do I do when my TA workload is more than expected?

ODD NUMBER in Cognitive Linguistics of WILLIAM CROFT and D. ALAN CRUSE

A word that means fill it to the required quantity

Dropping list elements from nested list after evaluation

If I score a critical hit on an 18 or higher, what are my chances of getting a critical hit if I roll 3d20?

Straighten subgroup lattice

Is it ok to offer lower paid work as a trial period before negotiating for a full-time job?

Old scifi movie from the 50s or 60s with men in solid red uniforms who interrogate a spy from the past

Does HR tell a hiring manager about salary negotiations?

How to display lines in a file like ls displays files in a directory?

Relationship between Gromov-Witten and Taubes' Gromov invariant

What is preventing me from simply constructing a hash that's lower than the current target?

Match Roman Numerals

What's the name of these plastic connectors

Pokemon Turn Based battle (Python)

Likelihood that a superbug or lethal virus could come from a landfill

What to do when moving next to a bird sanctuary with a loosely-domesticated cat?

Button changing its text & action. Good or terrible?

Accepted by European university, rejected by all American ones I applied to? Possible reasons?

What do hard-Brexiteers want with respect to the Irish border?

How come people say “Would of”?



JQuery - Slice/Remove - Special characters from ID or class name



The 2019 Stack Overflow Developer Survey Results Are InJavascript regex to remove illegal characters from DOM IDWhat is the best way to add options to a select from as a JS object with jQuery?Best way to remove an event handler in jQuery?How to remove close button on the jQuery UI dialog?How can I select an element with multiple classes in jQuery?How can I select an element by name with jQuery?How to remove all CSS classes using jQuery/JavaScript?Removing multiple classes (jQuery)Get selected text from a drop-down list (select box) using jQueryGet class name using jQueryjQuery Get Selected Option From Dropdown



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















For Japanese language, I am trying to get Japanese added dynamically from the backend.



I want to ignore the special characters, because I am getting "



Uncaught Error: Syntax error, unrecognized expression:


Is it possible to remove -(スーペリアルーム) from superior-room-(スーペリアルーム) and get only superior-room?



I need the output to be id="superior-room".



HTML:



 <div id =superior-room-(スーペリアルーム)" class="list-item">
<p>Title</p>
</div>


JS:



 var message = '';
var numAvailableRooms;
var roomContianerId = $('.list-item').attr('id');

if (numAvailableRooms < 100)
message = '50 rooms left!';
else
message = 'High demand!';


if (message == '')
$('#' + roomContianerId + ' .demand-message').hide();
else
$('#' + roomContianerId + ' .demand-message').show();
$('#' + roomContianerId + ' .demand-message').html(message);










share|improve this question
























  • Careful of: id =superior-room- you're missing an opening "

    – Mukyuu
    Mar 22 at 6:12

















2















For Japanese language, I am trying to get Japanese added dynamically from the backend.



I want to ignore the special characters, because I am getting "



Uncaught Error: Syntax error, unrecognized expression:


Is it possible to remove -(スーペリアルーム) from superior-room-(スーペリアルーム) and get only superior-room?



I need the output to be id="superior-room".



HTML:



 <div id =superior-room-(スーペリアルーム)" class="list-item">
<p>Title</p>
</div>


JS:



 var message = '';
var numAvailableRooms;
var roomContianerId = $('.list-item').attr('id');

if (numAvailableRooms < 100)
message = '50 rooms left!';
else
message = 'High demand!';


if (message == '')
$('#' + roomContianerId + ' .demand-message').hide();
else
$('#' + roomContianerId + ' .demand-message').show();
$('#' + roomContianerId + ' .demand-message').html(message);










share|improve this question
























  • Careful of: id =superior-room- you're missing an opening "

    – Mukyuu
    Mar 22 at 6:12













2












2








2








For Japanese language, I am trying to get Japanese added dynamically from the backend.



I want to ignore the special characters, because I am getting "



Uncaught Error: Syntax error, unrecognized expression:


Is it possible to remove -(スーペリアルーム) from superior-room-(スーペリアルーム) and get only superior-room?



I need the output to be id="superior-room".



HTML:



 <div id =superior-room-(スーペリアルーム)" class="list-item">
<p>Title</p>
</div>


JS:



 var message = '';
var numAvailableRooms;
var roomContianerId = $('.list-item').attr('id');

if (numAvailableRooms < 100)
message = '50 rooms left!';
else
message = 'High demand!';


if (message == '')
$('#' + roomContianerId + ' .demand-message').hide();
else
$('#' + roomContianerId + ' .demand-message').show();
$('#' + roomContianerId + ' .demand-message').html(message);










share|improve this question
















For Japanese language, I am trying to get Japanese added dynamically from the backend.



I want to ignore the special characters, because I am getting "



Uncaught Error: Syntax error, unrecognized expression:


Is it possible to remove -(スーペリアルーム) from superior-room-(スーペリアルーム) and get only superior-room?



I need the output to be id="superior-room".



HTML:



 <div id =superior-room-(スーペリアルーム)" class="list-item">
<p>Title</p>
</div>


JS:



 var message = '';
var numAvailableRooms;
var roomContianerId = $('.list-item').attr('id');

if (numAvailableRooms < 100)
message = '50 rooms left!';
else
message = 'High demand!';


if (message == '')
$('#' + roomContianerId + ' .demand-message').hide();
else
$('#' + roomContianerId + ' .demand-message').show();
$('#' + roomContianerId + ' .demand-message').html(message);







jquery






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 at 5:56









Philosophist

10410




10410










asked Mar 22 at 4:39









TDGTDG

5631624




5631624












  • Careful of: id =superior-room- you're missing an opening "

    – Mukyuu
    Mar 22 at 6:12

















  • Careful of: id =superior-room- you're missing an opening "

    – Mukyuu
    Mar 22 at 6:12
















Careful of: id =superior-room- you're missing an opening "

– Mukyuu
Mar 22 at 6:12





Careful of: id =superior-room- you're missing an opening "

– Mukyuu
Mar 22 at 6:12












3 Answers
3






active

oldest

votes


















0














Using pop and split you can get new id without (スーペリアルーム) and set new id to div like below.






var id = $('div').attr('id');
var arr = id.split("-");
//remove last element from array
var popItem = arr.pop();
//change array back to string and replace , with -
var result = arr.toString().replace(',','-');
//Give New ID for div
$('div').attr('id',result)
console.log($('div').attr('id'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id =superior-room-(スーペリアルーム)" class="list-item">
<p>Title</p>
</div>








share|improve this answer






























    1














    Using jQuery you can update only after page load, to update you can use attr() method. First of all, get all elements with an id attribute(use has attribute selector) and use attr() method with the callback to iterate and update id.



    $('[id]').attr('id', function(i, id)
    // replace all character except word char, digit and -
    // using negated character class in regex
    return id.replace(/[^wd-]/g, '');
    );



    To make it fully valid refer : Javascript regex to remove illegal characters from DOM ID.



    $('[id]').attr('id', function(i, id)
    return id.replace(/^[^a-z]+);





    share|improve this answer






























      0














      You can use javascripts splice to split at last occurrence of the hypen (-).






      var str = "superior-room-(スーペリアルーム)";
      var idx = "superior-room-(スーペリアルーム)".lastIndexOf('-');
      console.log(str.split('').splice(0,13).join(''));





      Hope this helps.






      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55293017%2fjquery-slice-remove-special-characters-from-id-or-class-name%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        0














        Using pop and split you can get new id without (スーペリアルーム) and set new id to div like below.






        var id = $('div').attr('id');
        var arr = id.split("-");
        //remove last element from array
        var popItem = arr.pop();
        //change array back to string and replace , with -
        var result = arr.toString().replace(',','-');
        //Give New ID for div
        $('div').attr('id',result)
        console.log($('div').attr('id'));

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <div id =superior-room-(スーペリアルーム)" class="list-item">
        <p>Title</p>
        </div>








        share|improve this answer



























          0














          Using pop and split you can get new id without (スーペリアルーム) and set new id to div like below.






          var id = $('div').attr('id');
          var arr = id.split("-");
          //remove last element from array
          var popItem = arr.pop();
          //change array back to string and replace , with -
          var result = arr.toString().replace(',','-');
          //Give New ID for div
          $('div').attr('id',result)
          console.log($('div').attr('id'));

          <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
          <div id =superior-room-(スーペリアルーム)" class="list-item">
          <p>Title</p>
          </div>








          share|improve this answer

























            0












            0








            0







            Using pop and split you can get new id without (スーペリアルーム) and set new id to div like below.






            var id = $('div').attr('id');
            var arr = id.split("-");
            //remove last element from array
            var popItem = arr.pop();
            //change array back to string and replace , with -
            var result = arr.toString().replace(',','-');
            //Give New ID for div
            $('div').attr('id',result)
            console.log($('div').attr('id'));

            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
            <div id =superior-room-(スーペリアルーム)" class="list-item">
            <p>Title</p>
            </div>








            share|improve this answer













            Using pop and split you can get new id without (スーペリアルーム) and set new id to div like below.






            var id = $('div').attr('id');
            var arr = id.split("-");
            //remove last element from array
            var popItem = arr.pop();
            //change array back to string and replace , with -
            var result = arr.toString().replace(',','-');
            //Give New ID for div
            $('div').attr('id',result)
            console.log($('div').attr('id'));

            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
            <div id =superior-room-(スーペリアルーム)" class="list-item">
            <p>Title</p>
            </div>








            var id = $('div').attr('id');
            var arr = id.split("-");
            //remove last element from array
            var popItem = arr.pop();
            //change array back to string and replace , with -
            var result = arr.toString().replace(',','-');
            //Give New ID for div
            $('div').attr('id',result)
            console.log($('div').attr('id'));

            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
            <div id =superior-room-(スーペリアルーム)" class="list-item">
            <p>Title</p>
            </div>





            var id = $('div').attr('id');
            var arr = id.split("-");
            //remove last element from array
            var popItem = arr.pop();
            //change array back to string and replace , with -
            var result = arr.toString().replace(',','-');
            //Give New ID for div
            $('div').attr('id',result)
            console.log($('div').attr('id'));

            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
            <div id =superior-room-(スーペリアルーム)" class="list-item">
            <p>Title</p>
            </div>






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 22 at 4:59









            ShreeShree

            12.9k2072124




            12.9k2072124























                1














                Using jQuery you can update only after page load, to update you can use attr() method. First of all, get all elements with an id attribute(use has attribute selector) and use attr() method with the callback to iterate and update id.



                $('[id]').attr('id', function(i, id)
                // replace all character except word char, digit and -
                // using negated character class in regex
                return id.replace(/[^wd-]/g, '');
                );



                To make it fully valid refer : Javascript regex to remove illegal characters from DOM ID.



                $('[id]').attr('id', function(i, id)
                return id.replace(/^[^a-z]+);





                share|improve this answer



























                  1














                  Using jQuery you can update only after page load, to update you can use attr() method. First of all, get all elements with an id attribute(use has attribute selector) and use attr() method with the callback to iterate and update id.



                  $('[id]').attr('id', function(i, id)
                  // replace all character except word char, digit and -
                  // using negated character class in regex
                  return id.replace(/[^wd-]/g, '');
                  );



                  To make it fully valid refer : Javascript regex to remove illegal characters from DOM ID.



                  $('[id]').attr('id', function(i, id)
                  return id.replace(/^[^a-z]+);





                  share|improve this answer

























                    1












                    1








                    1







                    Using jQuery you can update only after page load, to update you can use attr() method. First of all, get all elements with an id attribute(use has attribute selector) and use attr() method with the callback to iterate and update id.



                    $('[id]').attr('id', function(i, id)
                    // replace all character except word char, digit and -
                    // using negated character class in regex
                    return id.replace(/[^wd-]/g, '');
                    );



                    To make it fully valid refer : Javascript regex to remove illegal characters from DOM ID.



                    $('[id]').attr('id', function(i, id)
                    return id.replace(/^[^a-z]+);





                    share|improve this answer













                    Using jQuery you can update only after page load, to update you can use attr() method. First of all, get all elements with an id attribute(use has attribute selector) and use attr() method with the callback to iterate and update id.



                    $('[id]').attr('id', function(i, id)
                    // replace all character except word char, digit and -
                    // using negated character class in regex
                    return id.replace(/[^wd-]/g, '');
                    );



                    To make it fully valid refer : Javascript regex to remove illegal characters from DOM ID.



                    $('[id]').attr('id', function(i, id)
                    return id.replace(/^[^a-z]+);






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 22 at 4:51









                    Pranav C BalanPranav C Balan

                    90.1k1391118




                    90.1k1391118





















                        0














                        You can use javascripts splice to split at last occurrence of the hypen (-).






                        var str = "superior-room-(スーペリアルーム)";
                        var idx = "superior-room-(スーペリアルーム)".lastIndexOf('-');
                        console.log(str.split('').splice(0,13).join(''));





                        Hope this helps.






                        share|improve this answer



























                          0














                          You can use javascripts splice to split at last occurrence of the hypen (-).






                          var str = "superior-room-(スーペリアルーム)";
                          var idx = "superior-room-(スーペリアルーム)".lastIndexOf('-');
                          console.log(str.split('').splice(0,13).join(''));





                          Hope this helps.






                          share|improve this answer

























                            0












                            0








                            0







                            You can use javascripts splice to split at last occurrence of the hypen (-).






                            var str = "superior-room-(スーペリアルーム)";
                            var idx = "superior-room-(スーペリアルーム)".lastIndexOf('-');
                            console.log(str.split('').splice(0,13).join(''));





                            Hope this helps.






                            share|improve this answer













                            You can use javascripts splice to split at last occurrence of the hypen (-).






                            var str = "superior-room-(スーペリアルーム)";
                            var idx = "superior-room-(スーペリアルーム)".lastIndexOf('-');
                            console.log(str.split('').splice(0,13).join(''));





                            Hope this helps.






                            var str = "superior-room-(スーペリアルーム)";
                            var idx = "superior-room-(スーペリアルーム)".lastIndexOf('-');
                            console.log(str.split('').splice(0,13).join(''));





                            var str = "superior-room-(スーペリアルーム)";
                            var idx = "superior-room-(スーペリアルーム)".lastIndexOf('-');
                            console.log(str.split('').splice(0,13).join(''));






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 22 at 5:02









                            Priyesh DiukarPriyesh Diukar

                            35829




                            35829



























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55293017%2fjquery-slice-remove-special-characters-from-id-or-class-name%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                                Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript