How to remove numbers from a string?

前端 未结 7 1692
遇见更好的自我
遇见更好的自我 2020-12-12 19:56

I want to remove numbers from a string:

questionText = \"1 ding ?\"

I want to replace the number 1 number and the question mar

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 20:51

    String are immutable, that's why questionText.replace(/[0-9]/g, ''); on it's own does work, but it doesn't change the questionText-string. You'll have to assign the result of the replacement to another String-variable or to questionText itself again.

    var cleanedQuestionText = questionText.replace(/[0-9]/g, '');
    

    or in 1 go (using \d+, see Kobi's answer):

     questionText = ("1 ding ?").replace(/\d+/g,'');
    

    and if you want to trim the leading (and trailing) space(s) while you're at it:

     questionText = ("1 ding ?").replace(/\d+|^\s+|\s+$/g,'');
    

提交回复
热议问题