简体   繁体   中英

how to remove all text except one in javascript?

im trying to remove all text except one in javascript

the idea is do something like

//retrieve something like "cnode_72 cnode_1 layout_1  ui-datepicker-week-end "
// "ui-datepicker-week-end" is not necessary always present
var classes= jQuery("someelement").attr("class"); 

classes = classes.replace(/(?!ui-datepicker-week-end)/,'');

the expected ouput is :

ui-datepicker-week-end

Javascript (as per question)

Erm... might be missing something here, but how about:

classes = "ui-datepicker-week-end";

If that text isn't in the original string, and thus you don't want to add it if it isn't already there then try this:

if(classes.indexOf("ui-datepicker-week-end") == -1)
    classes = "";
else
    classes = "ui-datepicker-week-end";

JQuery (as per request in comments)

If by some bizarre reason you are using the jQuery("...").attr("class") but didn't bother mentioning that, then try this:

jQuery("...").removeAttr("class").addClass("ui-datepicker-week-end");

or with the condition:

if(jQuery("...").hasClass("ui-datepicker-week-end"))
    jQuery("...").removeAttr("class").addClass("ui-datepicker-week-end");
else
    jQuery("...").removeAttr("class");

Here is a working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM