Javascript find and replace function using while loop - javascript

I have this simple function to find and replace text in my textarea message. User will be able to type into the textarea and also be able to find and replace words from the text area they just entered. Currently I'm trying to use a while loop to replace multiple same words found in the textarea that the user keyed in. But every time I run it it seems to freeze the entire html page any idea why this is happening?
find and replace are textbox for user to key in the word they want to find and replace the user is able to key in multiple words to replace as well.
function findText() {
let find = document.getElementById('find').value;
let replace = document.getElementById('replace').value;
let message = document.getElementById('message').value;
var lmao = message.indexOf(find);
while (message.indexOf(find) != -1) {
document.getElementById("message").value = message.replace(find, replace);
}
}

Replace while loop with a replaceAll.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
function findText() {
let find = document.getElementById('find').value;
let replace = document.getElementById('replace').value;
let message = document.getElementById('message').value;
var lmao = message.indexOf(find);
document.getElementById("message").value = message.replaceAll(find, replace);
}
<div>Find <input id="find" value="find" /></div>
<div>Replace <input id="replace" value="replace" /></div>
<div>
<textarea id="message" style="height: 100px">you can find and replace every words just by .replaceAll, example: find 1 find 2 find 3</textarea>
</div>
<div>
<button onclick="findText()">Submit</button>
</div>

Just a addition in other answer you can use g for global search and to replace where you find that word .
Read more about regex and //g here
Also you can let the search case-insensitivity using i along with g like this :
message.replace(/find/g, replace)
This way it will also replace Find finD FIND
And instead of using while you can use if loop
function findText() {
let find = document.getElementById('find').value;
let replace = document.getElementById('replace').value;
let message = document.getElementById('message').value;
var lmao = message.indexOf(find);
if(message.indexOf(find) != -1) {
document.getElementById("message").value = message.replace(/find/g, replace);
}
}
<div>Find <input id="find" value="find" /></div>
<div>Replace <input id="replace" value="replace" /></div>
<div>
<textarea id="message" style="height: 100px">you can find and replace every words just by .replaceAll, example: find 1 find 2 find 3</textarea>
</div>
<div>
<button onclick="findText()">Submit</button>
</div>

The issue is with your while condition. When all input fields are empty your while condition is true. So inside the while condition the input value keeps on updating to empty string again, which makes loop an infinite loop. Thats why your ui is breaking.
Issue Scenario
console.log(("").indexOf("") !== -1);
To fix this, you have to make sure that your find and replace values are not same. Or else, it will be an infinite loop again.
Fixed Solution
function findText() {
let find = document.getElementById('find').value;
let replace = document.getElementById('replace').value;
let message = document.getElementById('message');
while (find !== replace && message.value.indexOf(find) != -1) {
message.value = message.value.replace(find, replace);
}
}
<input type="text" id="find">
<input type="text" id="replace">
<textarea name="" id="message" cols="30" rows="10"></textarea>
<button onclick="findText()">Check</button>

Related

Cannot get string of input from variable

So as said in last question i was making some console shet for my other stuff and got into some problems
i wanted to get string from input to variable to split it but it does not get anything, it's clear :\
this was my variable code
var args = consoleInput.value.split(/(\s+)/)
and then i wanted to see it using console log like this
console.log(args)
but output is this
>[""]
And nothing else
JS:
const consoleInput = document.getElementById("input");
var args = consoleInput.value.split(/(\s+)/)
console.log(args)
HTML:
<div class="inputTextDiv">
<span id="inputText"></span><br>
</div>
<input type="text" placeholder="Insert Command ;P" id="input">
I suspect the reason you were seeing an empty array is because you were running your code while the input field was empty.
Here I've attached it to fire whenever the input field receives input:
document.querySelector('input').oninput = () => {
const consoleInput = document.getElementById("input");
var args = consoleInput.value.split(/(\s+)/)
console.log(args)
}
<div class="inputTextDiv">
<span id="inputText"></span><br>
</div>
<input type="text" placeholder="Insert Command ;P" id="input">
(I also suspect that your regex ought to be /\s+/ instead of /(\s+)/, unless you really want to be capturing the spaces as part of the array.)

Javascript Regex - get variable from sentence

I want create simple AI for youtube in javascript. I want to write into input string like "Find Pranks on youtube". And that word "Prank" is variable... Everyone can write whatever thay want,but it must be sentence "Find 'something' on youtube". I tried to create regex, but it's to hard for me. Is it posible to do this like that?
The regex I tried is: \\Find\s\[abc]\s\\on\\youtube/i;
HTML Code:
<input type="text" id="uq" class="input auto-size"/>
<button id="button" onclick="question();" class="button" href="javascript:;">Ask</button>
Javascript Code:
function question()
const findonyoutube = /(?<=find)(.*)(?=on youtube)/gm;
var str = document.getElementById('uq').value;
if(findonyoutube.test(str))
{
alert(findonyoutube.exec(str)[0]);
}
}
Not working, it return Uncaught TypeError: Cannot read property '0' of null
To capture anything in between two words you can use:
function getVariable() {
const regex = /(?<=Find)(.*)(?=on youtube)/i;
let input = document.getElementById('myInput').value;
let match = regex.exec(input);
if(match) {
document.getElementById('debug').innerHTML = match[0];
return match;
} else {
return -1;
}
}
<h4>Example: Find ponies on youtube</h4>
<input type="text" id="myInput" />
<button onclick="getVariable();">Get Variable</button>
<br><br><hr>
<h3 id="debug"></h3>
It uses a positive lookahead and lookbehind to achieve this.

Use HTML input to replace information from string using Javascript

I'm trying to create a find and replace function that allows users to remove or replace symbols from strings that they input. I've found some found some answers online but I'm struggling to get them to work.
function myFunction(){
var input = document.getElementById("input").value;
var find = document.getElementById("find").value;
var regex = new RegExp("ReGeX" + find + "ReGeX");
var replace = input.replace(regex,"new");
console.log(replace)
}
<label style="margin:5px" style="padding:5px">Find & Replace</label><input style="marigin=5px" type="text" id="find">
<input type="text" id="input">
<button onclick="myFunction()">Submit</button>
Not sure but I are you trying to find and replace anything they entered with "new"? If so you don't need the one line(not sure that it works anyway), but this works. If they enter "old" in the input input and was to replace it with "new", can put "old" it in the find input and it will replace it with "new".
function myFunction(){
var input = document.getElementById("input").value;
var newTxt = document.getElementById("newTxt").value;
var find = new RegExp(document.getElementById('find').value, 'g')
//var regex = new RegExp("ReGeX" + find + "ReGeX");
var replace = input.replace(find,newTxt);
console.log(replace)
}
<label style="margin:5px" style="padding:5px">Find & Replace</label><input style="marigin=5px" type="text" id="find">
Replace with <input type="text" id="newTxt">
<input type="text" id="input">
<button onclick="myFunction()">Submit</button>

How to automatically change a specific text value with an input value?

What I'm trying to achieve is that when I'm entering an input value, the specific number of a textarea's value would replaced too according to the input value.
F.e: If I would enter into the input value a number 4, textarea's specific value (in this case a number) would be 4 too. If I would delete a value from the input, the value would be deleted from textarea too.
As you can see in the snippet, it works bad. It changes a value just one time. After that, 'text-areas' value isn't changing.
Could someone help me with that? Thank you for your time
$('.text1').keyup(function() {
var recommendationText = $('.textarea');
var specificString = '4';
var str = $('.textarea').val().replace(specificString, $(this).val());
recommendationText.val(str);
specificString = $(this).val();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="text1">
<textarea rows="4" class="textarea" cols="50">
This is a textarea of 4 rows.
</textarea>
There are a couple of issues with your code. The first is that the specificString value is being reassigned each time you do a keyup, so you need to set the default outside of the event handler. But also, if you delete the value, it will have no way of finding it and will prepend it to the start.
I'd personally recommend using a template based approach, rather than storing the previous value:
var specificString = '[numRows]';
var recommendationText = $('.textarea').val();
$('.text1').keyup(function() {
var numRows = $(this).val();
if (isNaN(parseFloat(numRows)) || !isFinite(numRows) || numRows.length < 1) {
numRows = 0;
}
var str = recommendationText.replace(specificString, numRows);
$('.textarea').val(str);
}).keyup();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="text1" value="4">
<textarea rows="4" class="textarea" cols="50">
This is a textarea of [numRows] rows.
</textarea>
This could use a proper templating language like Handlebars or Underscore.js templates, but that is too opinion-based to include in my answer.
Declare and initialize specificString outside of keyup() event.Otherwise your value for specificString will be always 4.
var specificString = '4';
$('.text1').keyup(function() {
var recommendationText = $('.textarea');
var str = $('.textarea').val().replace(specificString, $(this).val());
recommendationText.val(str);
specificString = $(this).val();
});
Well your issue is you replace the string so next time you look for the 4 it is not there. Reason why is you redefine specificString inside of the loop so it is always 4 and not what the user last typed. So if you move it outside it will work ("sort of")
Your design will fail if the user enters in something that matches another word. EG This, it will replace the first occurrence, not the string you want to replace. Or if you delete the string, you will not have any match.
So what can you do? I would use a data attribute with the original and use that. And I would make some sort of "template" so you know what you are replacing and do not replace another part of the string with the replacement when user matches text.
$('.text1').keyup(function() {
var ta = $('.textarea')
var specificString = /\{4\}/;
var entry = $(this).val() || "4";
var str = ta.data("text").replace(specificString, entry);
ta.val(str);
}).trigger("keyup");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="text1">
<textarea rows="4" class="textarea" cols="50" data-text="This is a textarea of {4} rows.">
</textarea>
In your way your code would work. Just change your code like this..! There are some logical issues in your code. Initiate the value of specificString outside the keyup() method to get first 4 and then then the value of textbox.
var recommendationText = $('.textarea');
var specificString = recommendationText.val().match(/\d+/);
$('.text1').keyup(function() {
if($(this).val() != '' && $.isNumeric($(this).val())) {
var str = $('.textarea').val().replace(specificString, $(this).val());
recommendationText.val(str);
specificString = $(this).val();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="text1">
<textarea rows="4" class="textarea" cols="50">
This is a textarea of 4 rows.
</textarea>
Solution is much easier than you might expect.
Note: The $ in ${inputVal} is not jquery, its part of template literals. Don't get confused there.
document.getElementById('text1').onkeyup = changeTextArea;
function changeTextArea() {
let inputVal = document.getElementById('text1').value;
let text = `This is a textArea of ${inputVal} rows`;
document.getElementById("textarea").value = text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="text1">
<textarea rows="4" id="textarea" cols="50">
This is a textarea of 4 rows.
</textarea>

How to go about parsing text for keywords in jQuery?

Say I had a famous speech posted on a website. What would be the best way to go about searching for a given keyword, say 'hello' throughout the entire document and save the number of occurrences as an integer? I don't really know where to start on this one. Should I use something like...
var wordcount;
$('#wrapper').each(function(e)
{
$("div:contains('hello')"){ //all content will be in the wrapper div
wordcount++;
});
});
I know that probably isn't right, but hopefully I'm on the right track. Thanks for the help!
The easiest way is to just return the length of a RegExp match:
var count = $("#wrapper div:contains('hello')").html().match(/hello/ig).length;
var numberOfMatches = $('div').text().match(/hello/ig).length;
Well unfortunately, that div:contains is only going to fire once. It is looking for all divs that contain that text. Unless you have every word wrapped in a div tag...
var text = $('#wrapper').text();
var words[] = text.split(' ');
var count = 0;
for(var i=0; i<words.length; i++){ if(words[i].IndexOf("TheWord") >= 0){ count++; } }
This is a non jquery method, but it should work for you.
If you're wanting to do this interactively (i.e., with a dynamic string), then this implementation is idiomatic:
http://jsfiddle.net/entropo/S5uTg/
JS ...
$("#keyword").keyup(function() {
var value = $(this).val(),
re = new RegExp(value, 'ig'),
count = $("#speech").text().match(re).length;
$("#result").text("Occurences: " + count);
});
HTML ...
<div id="search-form">
<legend>Search through this text</legend>
<label for="keyword">Keyword</label>
<input id="keyword" name="keyword" type="search"
placeholder="e.g. - today" required="" autofocus="" />
<div id="result"></div>
</div>

Categories