Simple replace with user input in JavaScript - javascript

I'm trying to make a 'find and replace' function that takes both values (replaced and replacement) from Form element and then replaces all occurances of 'replaced' inside DIV. After that I want it to display an alert with a replaced words count.
Tried to get there with the for loop, but something went wrong. Going with plain JS, I'm way too novice to get into jQuery.
function wordReplace()
{
var replaced = document.getElementById('replaced').value.toLowerCase;
var replacement = document.getElementById('replacement').value;
var workArea = document.getElementById('main').innerHTML;
for (var r=0; r<workArea.lenght; r++)
{
if (workArea[r].value.toLowerCase == 'replaced')
{
workArea[r].value.replace('\breplaced', 'replacement')
alert(workArea[r].value.replace('replaced', 'replacement').length)
}
}
}
And that's my form code, just in case: (ignore <input type="submit" onclick="replacerHide();"/> - it's for different function and it works for now)
<form>
<label for="replaced" class="labelInline">Słowo szukane</label>
<input type="text" name="replaced" id="replaced"/>
<label for="replacement" class="labelInline">Zamiennik</label>
<input type="text" name="replacement" id="replacement"/>
<input type="submit" onclick="replacerHide();"/>
</form>
I've read here (in a similliar question of mine) that I should get familliar with regex and I did. But have no faintest idea how to apply it to solve my problem. I'm pretty sure I'm onto something with for loop here, but other than that I'm empty :/
All and any help will be GREATLY appreciated.
EDIT - CORRECTED FULLY WORKING CODE
function wordReplace()
{
var div = document.getElementById('main');
var find = document.getElementById('replaced').value;
var replace = document.getElementById('replacement').value;
var re_Find = new RegExp(find, 'gi');
var matches = div.innerHTML.match(new RegExp(find, 'gi'));
if (matches)
{
div.innerHTML = div.innerHTML.replace(re_Find, replace);
}
matches = matches ? matches.length : 0;
alert(matches);
}
and for the Form
<div id="form">
<form id="formularz">
<label for="replaced" class="labelInline">Słowo szukane</label>
<input type="text" name="replaced" id="replaced"/>
<label for="replacement" class="labelInline">Zamiennik</label>
<input type="text" name="replacement" id="replacement"/>
<button onclick="replacerHide(); wordReplace();">Podmień!</button>
</form>
Now it's working as it is supposed to :)

Try some regexp.
function replace(find, replace, haystack) {
return haystack.replace(new RegExp(find,"gmi"),replace);
}
function count(find, haystack) {
return haystack.match(new RegExp(find,"gmi")).length;
}
window.alert(replace ("hello","bye","hello world? Hello person! and hello universe!"));
window.alert("Number of matches: "+count("hello","hello world? Hello person! and hello universe!"));

Regular expressions are your friend with things like this, as well as replace
By specifying the options gi to the RegExp constructor you can eliminate the need to check for character case (i means case-insensitive). The g means "global" and tells the regular expression you want to repeat the replacement for every instance of find that was found (by default, it will replace the first and then stop).
// Grab all of the necessary data
var div = document.getElementById('main');
var find = document.getElementById('replaced').value;
var replace = document.getElementById('replacement').value;
// Create our regular expression
var re_Find = new RegExp(find, 'gi');
// Get everything from the div's innerHTML that matches our regular expression
// (this will result in an array of strings, all of which are exactly
// the same as "find")
var matches = div.innerHTML.match(re_Find);
// If there were any matches, use the same regular expression to
// perform the actual replace and update the div
if (matches) {
div.innerHTML = div.innerHTML.replace(re_Find, replace);
}
// Grab the count of matches that were found and alert the user
matches = matches ? matches.length : 0;
alert(matches);

Related

Remove special characters from input field

I've been searching everywhere but have been unable to find exactly what I am looking for.
I have an html form that is filled out with Mac addresses from our inventory so the strings inputted into the input field will look like:
A1:A2:A3:A4:A5:A6
I'm trying to write a script to remove the : character plus any spaces anywhere. That way when it is entered the output will be:
A1A2A3A4A5A6
This is what I have so far:
<input type="text" id="macaddress" onChange="removeChar();WriteLog();" />
Then in my script I have:
function removeChar() {
var a = document.getElementById("macaddress").value;
a = a.replace(/: /g, '');
document.getElementById.innerHTML = a;
}
I don't get any JavaScript errors with this but nothing happens.
I also have another script that pulls the value of the field into a work log which is the other function WriteLog().
Essentially I want to remove the : then have the new value pulled into the log by the second function.
If you want to keep only numbers and letts you can use this
a.replace(/[^a-zA-Z0-9]/g, '');
which basically replaces everything that isn't a-z or A-Z or 0-9 with an empty string.
A great tool for explaining regex and testing it is Regex101
And this line document.getElementById.innerHTML = a; should be fixed as well, you probably meant something like document.getElementById('some-elements-id').innerHTML = a;
Question spec says you want to remove : and : with space. Make the space in the regex optional:
a = a.replace(/:( )?/g, '');
But you also need to account for preceeding spaces:
a = a.replace(/( )?:( )?/g, '');
I would also trim the initial string (Just good practice)
a = a.trim().replace(/( )?:( )?/g, '');
Finally, I am not sure what this line does:
document.getElementById.innerHTML = a;, but that line will throw an error. Remove it.
to remove colons and spaces from string simply use
str = str.replace(/[:\s]/g, '');
HTML
<input type="text" id="macaddress"/>
<button onclick="removeChar()">Click me!</button>
JS
function removeChar() {
var a = document.getElementById("macaddress").value.trim();
a = a.split('');
a.forEach(function (character, index) {
if (character === ':') {
a.splice(index, 1);
}
});
a = a.join('');
document.getElementById("macaddress").value = a;
}
Your Regex searches for "colon immediately followed by space".
If you add a pipe in between them: /:| /, then it will search for all colons and/or spaces, in any order.
Demo:
function removeChar() {
var a = document.getElementById("macaddress").value;
a = a.replace(/:| /g, '');
document.getElementById("result").innerHTML = a;
}
<input type="text" id="macaddress" onChange="removeChar();" />
<div id="result"></div>

Match keyword and extract line

I have a textarea where the user will enter multi-line input text and I want to go through it line by line and looking for specific keywords. Once the keyword is found, I want to extract from that keyword until the end of the line (i.e. new line reached).
I have the following code but it only extracts Sender: as output when the alert is executed. I am not really familiar with JavaScript so would really appreciate a better elegant approach than this.
function processFunction() {
var lines = document.getElementById("textarea").value.split('\n');
for(var i = 0;i < lines.length;i++){
extractSenderIP(lines[i]);
}
}
function extractSenderIP(someText) {
var re = new RegExp( "Sender:", "g" );
var result = re.exec(someText);
alert(result);
}
Your regex is only looking for the word "Sender:". You would need to tell it to find Sender: followed by anything to the next new line char:
var re = new RegExp( "Sender:.*\n", "g" );
At that point, you dont really even need to iterate around lines. The global regex should find all instances and return them in a collection.
Since you already split by newline split('\n'), you can check in your loop if your keyword matches and then get the line like this:
Sender:.*
Match Sender:
Match any character zero or more times .*
As an example:
function processFunction() {
var lines = document.getElementById("textarea").value.split('\n');
for(var i = 0;i < lines.length;i++){
extractSenderIP(lines[i]);
}
}
function extractSenderIP(someText) {
var re = new RegExp("Sender:.*", "g" );
var result = re.exec(someText);
if (result && result[0]) {
console.log(result[0]);
}
}
processFunction();
<textarea rows="4" cols="50" id="textarea">
Sender:test1
Sender:test1 Sender:test2
Sender: test2
test3</textarea>
re.exec returns an object with an index attribute, so you could do something like this:
result = re.exec(someText);
alert(someText.substring(result.index))

Using Java Script or jquery regex to verify if a string contains another string

I am building a simple search where query string can have wild cards '*'. Search terms can be like following:
animal
ani*
*mal
an*al
all above should return true if the word is 'animal'.
how this can be done in JS / jquery?
will appreciate for help.
rnv
The match on a string is simple:
var mystring = "This is my string";
var myregex = /*some regex*/
var results = mystring.match(myregex); // you can also write the regex directly as the argument of the match method, without using any variable.
So in your case you could have:
var mystring = "animal";
var myregex = new RegExp(inputQuery.replace(/\*/g, '.*'), 'gi'); // gi stands for 'global' and 'ignorecase' when applying the regex
var results = mystring.match(myregex);
Beware that .* matches zero or more (comes from the * whildcard) character, ANY character (comes from the .)
If you want to match zero or more letter, number or underscoreuse \w*, if you want to match one or more, use \w+, and if you want to match a specific number of letters, use \w{x} (\w{3} matches exactly 3 letters).
var str = "anim*";
var replaced = str.replace("*", ".*");
var regex = new RegExp(replaced);
var result = regex.test("animal");
console.log(result);
change the str variable to get the result as true or false;
Implemented version - https://jsfiddle.net/dpoqnacv/1/
var regexString = '^'+ $('#searchbox').val().replace("*",".*") + '$';
if(new RegExp(regexString).test('animal'))
$('#resultdiv').html('Matching...');
else
$('#resultdiv').html('Not Matching...');
You can just transform your wildcard into a RegExp and perform your search. Here is a simple example.
var search = document.getElementById("search");
var result = document.getElementById("result");
result.style.color = "red";
function fsearch() {
var str=search.value;
str = str.replace("*", ".*") //Transform your wildcard into a RegExp
result.innerHTML = "animal".match(new RegExp(str));
}
<label for="search">Search : <input name="search" id="search" type="text"/></label>
<input id="ok" type="button" value="ok" onclick="fsearch()"/>
Result : <div id="result"></div>
not bad answers but i think its easier with .test();
var str = "my dog is an animal";
/dog*anim*/.test(str); //returns true
/d*mal/.test(str); //returns true
etc
give it a try

How to capitalize first letter of every single word in a text area?

i have a multiline textfield("Adressfeld"), and i want to Uppercase every first letter and LowerCase the rest of every single word in this text area.
Here is my try:
function capitalize(Eingabe){
Eingabe = this.getField("Adressfeld").value;
var strArr = Eingabe.split(" ");
var newArr = [];
for(var i = 0 ; i < strArr.length ; i++ ){
var FirstLetter = strArr[i].charAt(0).toUpperCase();
var restOfWord = strArr[i].slice(1).toLowerCAse();
newArr[i] = FirstLetter + restOfWord;
}
return newArr.join(' ');
}
Ausgabe = this.getField("Empfängername");
Ausgabe.value = capitalize();
With the script shown above, every single word in the first line of the text area is capitalized. But in every other line, the first word isn't capitalized.
How i have to change the script to get it work?
Thanks,
I have included an example below try like that, it will solve your problem
Html
<input type="button" value="clk" onclick="z();"/>
<textarea rows="4" id="text" cols="50">
JS
function z()
{
var z=document.getElementById("text").value;
var x=z.replace(/\b./g, function(m){ return m.toUpperCase(); });
alert(x);
}
DEMO
I you want to Convert Every first letter of each word to upper and all other letters are lower then first convert the entire string to lowercase.Then do the same things as above.
DEMO2
Meinst du sowas?
var textToArray = document.getElementById('myTextarea').value.split('\n');
/* Hier eine Schleife zur Bearbeitung von textToArray */
var arrayToString = textToArray.join(' ');
The split operation fails -- the result of the first split cannot be split again on another character.
I see no reason to first replace returns by a single type \n and then try to split on either \n or a space. It's way easier to just replace the returns by a single space and only then split:
var strArr = String(Eingabe.value).replace(/[\r\n]+/g," ").split(" ");
With that, the rest seems to work.
Here is another approach, which may or may not work as well (it depends on whether Javascript's interpretation of "word boundary" \b agrees with your own):
function capitalize(Eingabe){
// Eingabe = this.getField("Adressfeld");
var strArr = String(Eingabe.value).replace(/[\r\n ]+/g,' ');
strArr = strArr.replace (/\b[a-z]/g, function(found) { return found.toUpperCase(); });
return strArr;
}
A few things:
• The argument of the function is Eingabe. In this case, this is a variable containing a value, and it does not make sense at all to redefine in the first line of the function. The way the function looks like, you won't need an argument, and therefore, your function definition looks like this:
function capitalize() {
• That done, define Eingabe properly as var Eingabe .
• With the array, you essentially want to create a two-dimensional array. First create the array of lines and then a loop through the lines, as it has been suggested in the answer by #Entimon
• You end with
this.getField("Adressfeld").value = capitalize() ;
And that should do it.
thanks for your help!
The correct answer is based on Arunprasanth KV's jsfiddle.net/svh1jd99
function capitalize()
{
var capitalize = this.getField("Adressfeld").value;
var done = capitalize.replace(/\b./g, function(m){ return m.toUpperCase();});
return done;
};
this.getField("Adressfeld").value = capitalize();
Thanks again for your help.
By using jQuery you can do this as shown below:
Demo: https://jsfiddle.net/cxow8198/3/
<input type="text" id="input">
<script>
//usage
$("input").keyup(function() {
toUpper(this);
});
//function
function toUpper(obj) {
var mystring = obj.value;
var sp = mystring.split(' ');
var wl=0;
var f ,r;
var word = new Array();
for (i = 0 ; i < sp.length ; i ++ ) {
f = sp[i].substring(0,1).toUpperCase();
r = sp[i].substring(1).toLowerCase();
word[i] = f+r;
}
newstring = word.join(' ');
obj.value = newstring;
return true;
}
</script>
Query code snippet to make capitals of the first letter of every word in the string. This could be used to prevent users from entering all caps for titles or text when they input data into forms.

Javascript regex with quotes

I need a way to replace all appearances of <br class=""> with just <br>
I'm a complete novice with regex, but I tried:
str = str.replace(/<br\sclass=\"\"\s>/g, "<br>");
and it didn't work.
What's a proper regex to do this?
I would not use a regex to do this, but rather actually parse the html and remove the classes.
This is untested, but probably works.
// Dummy <div> to hold the HTML string contents
var d = document.createElement("div");
d.innerHTML = yourHTMLString;
// Find all the <br> tags inside the dummy <div>
var brs = d.getElementsByTagName("br");
// Loop over the <br> tags and remove the class
for (var i=0; i<brs.length; i++) {
if (brs[i].hasAttribute("class")) {
brs[i].removeAttribute("class");
}
}
// Return it to a string
var yourNewHTMLString = d.innerHTML;
One way is with the following
var s = '<br class="">';
var n = s.replace(/(.*)(\s.*)(>)/,"$1$3");
console.log(n)
\s matches exactly one whitespace character. You probably want \s*, which will match any number (including zero) of whitespace characters, and \s+, which will match at least one.
str = str.replace(/'<br\s+class=\"\"\s*>/g, "<br>");

Categories