Remove text after JS character

Asked

Viewed 547 times

2

I need to remove everything in front of * (asterisk) Javascript example:

<form>
  <div class="form-row">
    <div class="col">
		<label>Carro</label>
      <input type="text" id="nome" class="form-control" value="palio*Azul">
    </div>
    <div class="col">
		<label>Resultado</label>
      <input type="text" id="resultado" class="form-control" >
    </div>
  </div>
	<input type="button" id="botaoapagar" onclick="apagar();" value="Apagar">
	
</form>

<script>

function apagar(){


var nome = document.getElementById("nome").value;

// Exemplo retornando só o modelo
var resultado = "palio"

 document.getElementById("resultado").value = resultado;



}</script>

2 answers

4


Just use the method split() to cut the string at the first occurrence of the asterisk, as shown below:

var resultado = nome.split("*", 1);

In the above code, the first method parameter split() is the sought character (in this case the asterisk) and the second is the occurrence (in this case the first occurrence).

Below is a demonstration of the use of the method in question in its code:

<form>
  <div class="form-row">
    <div class="col">
		<label>Carro</label>
      <input type="text" id="nome" class="form-control" value="palio*Azul">
    </div>
    <div class="col">
		<label>Resultado</label>
      <input type="text" id="resultado" class="form-control" >
    </div>
  </div>
	<input type="button" id="botaoapagar" onclick="apagar();" value="Apagar">
	
</form>

<script>

function apagar(){


var nome = document.getElementById("nome").value;
//Função split para cortar a string no primeiro asterisco encontrado
var resultado = nome.split("*", 1);

document.getElementById("resultado").value = resultado;



}</script>

4

With .substr() and indexOf() you can catch the start substring (index 0) up to the first occurrence of the asterisk (the indexOf() goes to the character before the occurrence):

var resultado = nome.substr(0, nome.indexOf("*"));

Example:

function apagar(){
  var nome = document.getElementById("nome").value;

   // Exemplo retornando só o modelo
   var resultado = nome.substr(0, nome.indexOf("*"));

   document.getElementById("resultado").value = resultado;
}
<input type="text" id="nome" class="form-control" value="palio*Azul">
    </div>
    <div class="col">
		<label>Resultado</label>
      <input type="text" id="resultado" class="form-control" >
    </div>
  </div>
	<input type="button" id="botaoapagar" onclick="apagar();" value="Apagar">

Browser other questions tagged

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