I have this if condition where if you’re input "[first_name]" in the text field the result will be "John". But if you’re input "Hello [first_name]" the result will be "Hello [first_name]".
Here’s the code, i know if you’re input only "[first_name]" in text field it works. But how do i fix this if i write whatever in the text field the result would be what i write and the variable "[first_name]" would be "John". Thank you.
<p> Input [first_name] for variable </p>
<input id="myInput" type="text">
<button onclick="myFunction()">Enter</button>
<p id="result"></p>
function myFunction(){
var input = document.getElementById("myInput").value;
var myVar = "[first_name]"
if (input == myVar){
var data = document.getElementById('result').value= "John"
document.getElementById("result").innerHTML = data;
}
else{
document.getElementById("result").innerHTML = input
}
}
What Did I Tried
Input field:
Hello [first_name]
Result:
Hello [first_name]
What I’m Expecting
Input field:
Hello [first_name]
Result:
Hello John
or whatever i write in the text field with variable "[first_name]" would be "John" and another text that i write.
>Solution :
You need to modify your JavaScript code slightly. Instead of comparing the entire input string with "[first_name]", you should check if "[first_name]" is present in the input string using the indexOf() method. Here’s the modified code:
function myFunction(){
var input = document.getElementById("myInput").value;
var myVar = "[first_name]";
if (input.indexOf(myVar) !== -1){
var data = input.replace(myVar, "John");
document.getElementById("result").innerHTML = data;
}
else{
document.getElementById("result").innerHTML = input;
}
}
<p>Input [first_name] for variable</p>
<input id="myInput" type="text">
<button onclick="myFunction()">Enter</button>
<p id="result"></p>