Regex or Replace in Jquery

Asked

Viewed 630 times

1

How to make a string change 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.

2 answers

2


Replacing the <span> for <input> and using the plugin Jquery.Mask you can do it:

<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>
<script src="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>

Reference of Jquery.Mask

0

There are 3 errors in your script:

  1. $(#number) missing quotation marks in #number
  2. $(...) returns a jQuery OBJECT, so there is no method .replace, this method belongs to the String.prototype (javascript native)
  3. Closing tags are wrong:

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

    Should be:

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

The correct should probably be used text or html which are jQuery methods, so:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div><span id="number">1195555666</span></div>
    
<script>$('#number').text('(11)95555-6666')</script>

If you want to take the console.log do so:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div><span id="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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.