Replace part of a string with another string javascript - javascript

what I have is 3 text boxes. The first one a user enters a string. The second box they enter part of the first string they want to replace. The third text box is the string that is to do the replacing.
I'm trying to use the replace() method but I dont think Im using it right or i should be using something else.
html:
<form>
Enter a string:<input type="text" id="user_string"><br>
Enter portion of previous string to be replaced: <input type="text" id="replace_string"><br>
Enter new string: <input type="text" id="add_string"><br>
<input type="button" value="Execute" onclick="BaitAndSwitch()"><br>
Result: <input type="text" id="req_4_results"><br>
</form>
Javascript:
function BaitAndSwitch(){
// create variables for the user entered data
var UserString = document.getElementById("user_string").value;
var ReplaceString = document.getElementById("replace_string").value;
var AddString = document.getElementById("add_string").value;
var Results = UserString.replace(ReplaceString, Addstring);
if (UserString.indexOf(ReplaceString) > -1) {
Document.getElementById("req_4_results").value = Results;
}
else{
alert("Something went wrong! Please check the data you entered.")
}
}
I know I'm doing something wrong. Maybe the use of variables in the .replace() method? Or maybe the if... using indexOf line?
I was essentially trying to set it up where it would check UserString with the value of ReplaceString and if it matched, it would then execute the replace() method and show results to the given HTML element. Else if the ReplaceString didn't match any thing from UserString, it would alert the user something was wrong and to check it.

JavaScript is cAsE SeNsItIvE. Please note that Document is not the same as the document object. Please use the below line:
document.getElementById("req_4_results").value = Results;
Oh and yes, as pointed out by blex, you have another typo too:
var Results = UserString.replace(ReplaceString, Addstring);
//-------------------------------------------------^ should be S
More Info: In the console, if you try both, see the result you get:
typeof Document
// "function"
typeof document
// "object"
On a side note, please do not use such Naming Conventions. Looks like you are migrating from Visual Basic.

Note that the replace() method does not modify the string that you call it on.
In your line of code:
var Results = UserString.replace(ReplaceString, Addstring);
The value of UserString will not changed as a result of having called replace() on it.
In your conditional statement:
UserString.indexOf(ReplaceString) > -1
If it is true, it means that UserString still contains at least one instance of ReplaceString within it.
That makes sense, because you wouldn't have modified UserString yet. If you want to make sure that Results no longer has any occurrence of ReplaceString, then you want to throw an error only if the following condition is true:
Results.indexOf(ReplaceString) > -1

Related

multiplication inside an input with "*" operator

I am trying to get a multiplication entered in an input replaced by its solution.
Basicaly, when you enter 3*3 into the input, I would like my javascript code to replace 3*3 by 9.
Probably not so hard to obtain but I'm a total noob with javascript here. I get this so far, but I should miss a crucial point!
Thanks for your help :)
function multiply() {
var string = document.getElementById("mult").value;
var array = string.split("*");
var res = Number(array[0]*array[1]);
document.getElementById("res").value = res;
}
input{width:80px; text-align:right;}
input[readonly]{border:0;}
entrer: <input type="text" id="mult" onblur="multiply()">
<br>result: <input type="text" id="res" readonly>
Your code actually works as it is now. Just make sure you tab out of the input field after typing in the equation and you'll see it do its job. That's because your code is running on the blur event, which is when the focus leaves an element.
But, as far as your conversion code goes:
Number(array[0]*array[1])
Attempts to convert the product of array[0] and array[1], when what you need is to convert each array value to a number first and then do the math.
Number(array[0]) * Number(array[1])
Now, instead of Number(), you can just prepend a + to each value that needs conversion.
+array[0] * +array[1]
But, in reality, anytime you attempt to do multiplication, division or subtraction on strings, they are automatically converted to numbers, so you really don't even need that here.
Lastly, since you are just displaying the result and don't want the user to be able to modify it, just put it into a regular element, like a span instead of a form field element that you then have to set to readonly. Form fields are primarily for collecting information, not displaying it. When you do work with a non-form field element, you don't use the value property, you use .textContent (when there is straight text) or .innerHTML (when the string contains HTML to be parsed).
function multiply() {
var string = document.getElementById("mult").value;
var array = string.split("*");
var res = array[0] * array[1];
document.getElementById("res").textContent = res;
}
input{width:80px; text-align:right;}
input[readonly]{border:0;}
entrer: <input type="text" id="mult" onblur="multiply()">
<br>result: <span id="res"></span>

Is there any way to detect and change the input value format?

I am checking and validating the text area value with a regex
and I want to change the formating like this:
user input:
123456
change to:
12/34/56
can this be done in pure js?
edit:
this is what I did yet:
function changeIt() {
var inputChanger = document.getElementById("id").value.replace(something , something);
document.getElementById("id").value = inputChanger;
}
but no idea how to proceed
Try something like this:
Note: for this code to work, the HTML must come before the JavaScript, but stack overflow apparently re-order's code snippets to always show the JS first (?)
var input = document.getElementById('my-input');
function format() {
// \d matches a digit,
// parenthesis let you use the matched values as $n in the replacement string
input.value = input.value.replace(/(\d\d)(\d\d)(\d\d)/, '$1/$2/$3');
}
// you probably only need one of these, but it doesn't hurt to have both
input.addEventListener('change', format);
input.addEventListener('keyup', format);
<input type="text" id="my-input" />
It can also, of course, be done with some jQuery and maybe a plugin like http://jquery-plugins.net/maskjs-jquery-plugin-to-mask-inputs - but I think it's good to understand what's happening under the hood even if you end up going that way.

Alternative in regular expression's ending

I have the following DOM structure:
<form>
<input type="text" id="a">
<button>Submit</button>
</form>
or:
<form>
<input type="text" id="a">
</form>
which one depends on what user have done, it's created dynamically.
I want to be able to add another input right below the previous one (it can not exist yet and be the first one). To do that, I wanna get all text until the place I'm adding new input. How can I get that text using regex?
I tried the following:
'(.*?)[<button.*?>Submit<\/button><\/form>|<\/form>]'
But it doesn't work, because it displays empty string as a result.
var afterRegex = new RegExp('(.*?)[<button.*?>Submit<\/button><\/form>|<\/form>]', 'i');
var appendAfter = $(".downloadCode textarea").val().match(afterRegex)[1];
alert(appendAfter);
I'm a little confused by your code, but, based on what you've said (and that you've tagged your question with jQuery), I think that you can accomplish what you are trying to do with this code:
var $newInput = **CREATE_YOUR_NEW_INPUT_ELEMENT_HERE**;
var $form = $("form");
var $lastInput = $form.find("input:last");
// no inputs, make the new input the first element in the form
if ($lastInput.length < 1) {
$form.prepend($newInput);
}
// at least on existing input, add the new input after the last one
else {
$lastInput.after($newInput);
}
You should not parse HTML using Regexp. No, seriously.
That being said, the correct syntax for multi-character alternatives is (?:alternativeA|alternativeB):
(.*?)(?:<button.*?>Submit<\/button><\/form>|<\/form>)
Note that this does not work if you have whitespace characters in between. Yet another reason not to use Regexps here.

Replace Word Within Word - Javascript

I need to get a id from a html element and replace a part of the word. For example:
HTML
<input type="checkbox" id="facebookCheckbox"></div>
JavaScript
var x = document.getElementById("facebookCheckbox");
var name = x.id;
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced. Is there a different way of doing this?
I'm looking for purely javascript no jQuery
Thank you!
name.replace("Checkbox","");
This obviously does not work because the replacing word has to be standalone for it to be replaced.
No, it does work and there's no need to be "standalone" - any part of the string can be matched. Only you did nothing with the result of the operation:
console.log(name.replace("Checkbox",""));
// or
name = name.replace("Checkbox","");
// or assign back to x.id maybe?
You are creating a copy of string when replacing, so you must assign the result of .replace() back to x.id.
var x = document.getElementById("facebookCheckbox");
x.id = x.id.replace("Checkbox","");
this is not going to work in this way. However you can have a marker kind of character by which you can break the name into array and implement the logic. For example:
var x = document.getElementById("facebook_Checkbox");
//Note I have added underscore in the Id
var name = x.id;
var arr=name.split("_");
//Now you have Checkbox and Facebook as string objects (part of array) and you can use them
name=arr[0]
I hope it will solve the purpose.

HTML DOM element name as a string

Suppose I have the following HTML snippet:
<input type="text" id="myinput" />
Now I want to get that DOM element using JavaScript:
var element = document.getElementById("myinput");
Works fine, no problem so far.
But when I print it inside an alert box using alert(element);, it displays object HTMLInputElement.
Is there a way to get that element name (HTMLInputElement) as a string?
(Notice that when saying "element name" I do not mean the name attribute of an element, but the name how it is displayed when using alert() for example, as described above.
In some browsers, such as Firefox (and Chrome, potentially others) you can do:
element.constructor.name; // => "HTMLInputElement"
But in general it's a bit more complicated, perhaps not even totally reliable. The easiest way might be as such:
function getClassName(o) {
// TODO: a better regex for all browsers...
var m = (o).toString().match(/\[object (.*?)\]/);
return (m) ? m[1] : typeof o;
}
getClassName(element); // => "HTMLInputElement"
getClassName(123); // => "number"
[Edit]
Or, using the "nodeName" attribute, you could write a utility function which should be generally much more reliable:
function getHtmlElementClassName(htmlElement) {
var n = htmlElement.nodeName;
if (n.matches(/^H(\d)$/)) {
return "HTMLHeadingElement";
} else if (/* other exceptional cases? */) {
// ...
} else {
return "HTML" + n.charAt(0) + n.substr(1).toLowerCase() + "Element";
}
}
(Thanks #Esailija for the smarter implementation, #Alohci for pointing out exceptional cases.)
alert(element.nodeName);
https://developer.mozilla.org/En/DOM/Node.nodeName
When passing an object to the alert() function, it implicitly calls .toString() on that object in order to get the text for the alert. You could do something like:
var element = document.getElementById("myInput");
var string = element.toString(); // this will return 'object HTMLInputElement'
then work with the string variable to get only the HTMLInputElement part.
if I've got the question correctly you should try document.getElementById("myinput").toString().
document.getElementById returns the HTML element as an object. Simply get the attribute of the object you want to display in the alert instead (e.g., alert(element.getAttribute('ID'));). Alternatively, if you want '[object HTMLInputElement]' displayed in the alert, simply call the toString() method on the object in the alert (e.g., alert(element.toString());).
Hope this helps,
Pete

Categories

Resources