Regex or Replace in Jquery

1

How do I change a string by adding new content?

Example:

<div><span id="number">1195555666<span><div>

<script>var newNumber = $(#number).replace('(11)95555-6666')</script>
console.log(newNumber);

But the number is a variable, so replace does not work.

    
asked by anonymous 20.05.2018 / 15:46

2 answers

2

Replacing <span> with <input> and using the Jquery.Mask plugin you can:

<div>
    <input type="text" name="number" id="number" value="1195555666">
</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
<script type="text/javascript">
    $('#number').mask('(00) 00000-0000');
</script>
  

Jquery.Mask

    
20.05.2018 / 16:01
0

You have 3 errors in your script:

  • $(#number) missing quotes in #number
  • $(...) returns a jQuery OBJECT, so there is no .replace method, this method belongs to String.prototype (JavaScript native)
  • The closing tags are wrong:

    <div><span id="number">1195555666<span><div>
    

    Should be:

    <div><span id="number">1195555666</span></div>
    
  • The correct one should probably be to use text or html which are jQuery methods, like this:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><spanid="number">1195555666</span></div>
        
    <script>$('#number').text('(11)95555-6666')</script>

    If you want to get the value in console.log do so:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div><spanid="number">1195555666</span></div>
        
    <script>
    var antigo = $('#number').text(); //Pega valor antigo
    
    $('#number').text('(11)95555-6666'); //Seta valor novo
    
    var novo = $('#number').text(); //Pega valor novo
    
    console.log(antigo);
    console.log(novo);
    </script>
        
    23.05.2018 / 18:26