简体   繁体   中英

.replace not removing characters

So I'm trying to convert PX to EM, but if a user enters 16px , instead of 16 I want to strip the PX . Here's what I'm using

.replace(/^EM+/i, '')

But for some reason it's not removing.

Here's a demo . Enter any value with PX , and you'll get NaN . Also is there a way to suppress the NaN so that then it won't show?

我对此的理解是^字符指定了行的开头, +字符指定必须至少有一个... 这个例子有效

.replace(/EM+/i, '')

Forked fiddle: http://jsfiddle.net/FDkLa/

Don't use ^ as it tells to match beginning of the string.

The ^ matches the start of the string, so this will only remove px in the start. Use this instead:

.replace(/EM/i, '')

The + is also unnecessary; M+ it matches 1 or more M's (eg "EMMM" matches).

There you go.

strips all characters leaving only numbers. And no more NaN.

EDIT: Ok, fixed the problem with the huge number.

Confirm here Latest Version

$(document).ready(function () {
  $('.px').keyup(function () {
    var px = $(this).val().replace(/\D/g,'');
    var rep = (px / 16);
    $('.em').val(rep);            
  });    
  $(".em").keyup(function () {
    var em = $(this).val().replace(/\D/g,'');
    var rem = (em * 16);
    $('.px').replace().val(rem);
  });     
});

You might want to try something like this inside your event listener:

var val = this.value;
if (/^\d+(?:px)?$/i.test(val)) {
    // do conversion stuff
} else {
    // display error to user, perhaps a red border on the input
}

The easiest method is probably to just remove all characters that aren't [0-9\\.] (a period or a number) on keyup . Then, you can perform the calculations and update the <input> s.

fiddle

HTML

px <input type="text" id="px"> <br>
em <input type="text" id="em">

JavaScript

$("#px").keyup(function () {
    var px = $(this).val().replace(/[^\d\.]+/g, "");   // replace all non 0-9 or .
    $(this).val(px);
    $("#em").val(parseInt(px)/16);               // set the value of em to px/16
})
$("#em").keyup(function(){
    var em = $(this).val().replace(/[^\d\.]+/g, "");  // replace all non 0-9 or .
    $(this).val(em);
    $("#px").val(parseInt(em) * 16);            //set the value of px to em*16
})

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