Javascript match and extract $ symbol from a string?

后端 未结 4 849
孤街浪徒
孤街浪徒 2021-01-24 02:55

Currently I have:

var price = \'$4000\';
var currency = price.match([\\$]);
alert(currency);

However this doesn\'t seem to work. I would like t

相关标签:
4条回答
  • 2021-01-24 03:29

    If you want to find the dollar sign in any position use:

    var currency = price.match(/\$/);
    

    If you want to find the dollar sign at the beginning of the string use:

    var currency = price.match(/^\$/);
    

    Here's the documentation about Javascript RegExp

    0 讨论(0)
  • 2021-01-24 03:43

    Put your regular expression inside // or quotes:

    var price = '$4000';
    var currency = price.match(/[\$]/);
    alert(currency);
    
    0 讨论(0)
  • 2021-01-24 03:50

    Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. (c) Jamie Zawinski

    I agree that RegEx is more concise but you could do with just '$4000'.indexOf('$'). Like this:

    if (price.indexOf('$')>-1) { currency = '$' }
    
    0 讨论(0)
  • 2021-01-24 03:53

    This should work: '$4000'.match(/^\$/).

    (It looks for the $ sign at the beginning of the string)

    The javascript syntax for regular expression literal uses / at the beginning and at the end of the expression.

    0 讨论(0)
提交回复
热议问题