0

I have this div:

<h1>$340</h1>

I need to detect if inside of this div there is a dollar symbol,
If so - remove it


I'll explain again: I have got this code so far so I manage to detect if the symbol is in the div, but I can't figure how to remove it and update the DOM?

var sign = $('h1').text();

    if (sign.indexOf("$") >= 0) {
     //remove the sign
    }
user4571629
  • 440
  • 3
  • 10
  • 24
  • possible duplicate of [How to see if string contains substring](http://stackoverflow.com/questions/3480771/how-to-see-if-string-contains-substring) – gmo Mar 24 '15 at 12:51

8 Answers8

2

This is quite easy using a simple regex

var div = $('your selector here');
div.html(div.html().replace(/\$/g, ''));
MarshallOfSound
  • 2,629
  • 1
  • 20
  • 26
1

That's what I have meant, without the If condition:

$('h1').text( $('h1').text().replace("$", ''));  
user4571629
  • 440
  • 3
  • 10
  • 24
0

Try like this

var price = $("h1").html().replace(/[^\d\.]/g, '');
console.log(price);
I'm Geeker
  • 4,601
  • 5
  • 22
  • 41
0

Something like this should work:

$("h1").each(function() {
  var $el = $(this);
  var text = $el.text().replace("$", "");
  $el.text(text);
});
Juan G. Hurtado
  • 2,057
  • 16
  • 25
0
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Dialog - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$( document ).ready(function() {  
    var val=$('#demo').html().replace('$','');
  $( "div" ).replaceWith( val );
});
</script>
</head>
<body>
<h1 id='demo'>$540</h1>
</body>
</html>
dhruv jadia
  • 1,684
  • 2
  • 15
  • 28
-1

Jquery can select based on contents. See https://api.jquery.com/contains-selector/.

What you need to do is:

$( "div:contains('$')" ).remove();
-2

$(function() {
  $("#button").click(function() {
    var input = $("#input").val();
    input = input.replace('$', '');
    $("#input").val(input);
  });
});
<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <title></title>
    <meta charset="utf-8" />
  </head>
  <body>
    <input type="text" id="input" placeholder="type here..." />
    <button id="button">Remove</button>
  </body>
</html>

This is the JQuery approach, I used replace on click on button to remove $ from input.

Anwar
  • 4,162
  • 4
  • 41
  • 62
-4
function HasDollar() {   
 if($("h1").html().indexOf("$") != -1) 
       return true;
    else
       return false;
}

try this.

Douglas Franco
  • 591
  • 5
  • 13
  • Why should the OP "try this"? Please add an explanation of what you did and why you did it that way not only for the OP but for future visitors to SO. – Jay Blanchard Mar 24 '15 at 14:07