Assigning an id to a regex pattern - javascript

I need to assign an ID into a pattern so that someone could write something in my first text field, and then write a key word in the second textfield, then the key word will be the pattern searched by the RegExp.
JavaScript
function getInput(textfield)
{ // get value from field
var inString = document.getElementById("string").value;
var inSubstring = document.getElementById("substring").value;
// search for pattern
var patt1 = /Id/g;
// document.writeln(patt1);
var result = inString.match(patt1);
// choose paragraph and write the result
document.writeln(result);
// document.getElementById("Answer").innerHTML = result;
}
HTML
<body>
<form id="form1" name="form1" method="post" action="">
<label>Enter a string
<input id="string" name="string" type="text" />
</label>
<input name="Button" type="submit" value="Submit" id="Button" onclick="getInput('textfield')" />
<br />
<br />
<label>Enter a substring to search
<input id="substring" name="substring" type="text" />
</label>
</form>
<p id="Answer"> </p>
</body>

Use a RegExp object instead of an inline regex :
function getInput(textfield)
{ // get value from field
var inString = document.getElementById("string").value;
var inSubstring = document.getElementById("substring").value;
// search for pattern
var patt1 = new RegExp(inSubstring, "g");
// document.writeln(patt1);
var result = inString.match(patt1);
// choose paragraph and write the result
document.writeln(result);
// document.getElementById("Answer").innerHTML = result;
}

I believe you want this regex to change:
var patt1 = /Id/g;
And support a variable id to be searched.
You can use RegExp object with word boundaries:
var patt1 = new RegExp('\\b' + id + '\\b', 'g');
OR else you can just dump the regex and use String#indexOf like this:
index = inString.indexOf(id);

Related

Uncaught TypeError: projected.value is undefined

I'm currently trying to build a find and replace program using regular expressions in JavaScript, but I keep getting the following error when I click the "go" button, which is supposed to find and replace the given string, although currently all I'm trying to do is print the found string onto the console:
Uncaught TypeError: projected.value is undefined
Here's the code:
<body>
<textarea name="input" id="inputText" cols="30" rows="10">
</textarea>
<p id="projectedText"></p>
<label for="find">Find: </label>
<input type="text" id="find">
<label for="replace">Replace: </label>
<input type="text" name="" id="replace">
<input type="button" value="Go" id="commit">
</body>
document.getElementById("commit").onclick=findNreplace; //set up go button
//variables
var textToShow = document.getElementById("inputText");
var projected = document.getElementById("projectedText");
var toFind = document.getElementById("find").value;
var toReplace = document.getElementById("replace").value;
// set up text area to project the input into the paragraph
textToShow.addEventListener('input',updateValue);
function updateValue(text) {
projected.textContent=text.target.value;
}
// replace function
function findNreplace() {
var regex = /toFind/;
var found = projected.value.match(regex);
console.log(found);
}
What am I missing?
The <p> element does not have a value property, but you can access its value the same way you updated it with the textContent property.
To match the value of the toFind input instead of exactly matching the "toFind" string, you need to use the variable in the regex.
function findNreplace() {
var regex = new RegExp(toFind, 'g');
var found = projected.textContent.match(regex);
console.log(found);
}
You could also just reuse the input value directly:
function findNreplace() {
var regex = new RegExp(toFind, 'g');
var found = textToShow.value.match(regex);
console.log(found);
}
You will also need to change the element selectors if you intend to get the current value of the inputs in the functions instead of just getting the initial value when the script loads:
var toFind = document.getElementById("find");
var toReplace = document.getElementById("replace");
Update the function to get the current value of the input when it's called:
function findNreplace() {
var regex = new RegExp(toFind.value, 'g');
var found = textToShow.value.match(regex);
console.log(found);
}
At end of this line "var projected = document.getElementById("projectedText")" write .value

Form Text Area creates a URL

I have a pretty simple need here.
I want to have a text area, that is populated with a line of ID's - each id will be on a new line.
How can I generate a URL from that?
12345
09876
Once submitted should generate to be https://xx.com/12345&09876
I have been using this Form value creates a URL and have changed it to text area, but cant get each line break to be changed to the '&' in the url string.
Any help would be amazing!
<script type="text/javascript">
function goToPage() {
var page = document.getElementById('page').value;
window.location = "https://google.com/" + page;
}
</script>
<textarea name="textarea" style="width:250px;height:150px;" id="page"></textarea>
<input type="submit" value="submit" onclick="goToPage();" />
You can split by \n to get the characters in each line and join by &, then remove the last character:
var url = txt.value.split("\n").join("&").slice(0, -1);
console.log(url);
<textarea id="txt">
12345
09876
</textarea>
In the case of a form:
txt.addEventListener('input', function(){
form.action = txt.value.split("\n").join("&").slice(0, -1);
console.log(form.action);
})
<textarea id="txt">
12345
09876
</textarea>
<form id="form">
<button>Submit</button>
</form>
In your particular case:
<textarea name="textarea" style="width:250px;height:150px;" id="page"></textarea>
<input type="submit" value="submit" onclick="goToPage();" />
<script type="text/javascript">
function goToPage() {
var page = document.getElementById("page").value.split("\n").join("&");
alert(page);
window.location = "https://google.com/" + page;
}
</script>
You can replace text in a string using the JavaScript replace function, as follows:
var newString = oldString.replace(/(\r\n|\r|\n)/g, '&');
This line takes the string variable oldString (which should contain the data with all of the linebreaks) and changes all of the linebreaks to ampersands. It uses something called a Regular Expression to find all of the line breaks.
So for your HTML:
<script type="text/javascript">
function goToPage() {
var page = document.getElementById('page').value;
window.location = "https://google.com/" + page.replace(/(\r\n|\r|\n)/g, '&');
}
</script>
<textarea name="textarea" style="width:250px;height:150px;" id="page"></textarea>
<input type="submit" value="submit" onclick="goToPage();" />
try splitting your text area by \n by doing so:
var split_text = your_text_area.split("\n"); // Replace your_text_area
The string which will be passed in the text area will be splitted by \n (newline) and every line will be inserted in the split_text variable, which is an array.
Then, you can generate a URL from the array like this:
var url = '';
for(let i = 0; i < split_text.length; i++)
{
url += split_text[i];
if((i+1) != split_text.length) // <-- Not the most optimized way to do it
{
url += "&";
}
}

Censoring / Highlighting using JavaScript

I'm trying to create a small sample application for highlighting / censoring of a textarea using JavaScript. To start with I'm just trying to replace the letters, though once that is solved my plan was to use mark.js to mark censored words. Right now when I run my application I'm getting Uncaught TypeError: Cannot Read property 'value' of null on line 21.
<html>
<head>
<title>Syntax Highlighting</title>
</head>
<body>
<form name="badwords" method="post" action="" >
<textarea name="comments" rows="10" cols="60"></textarea>
<br />
<input id="formSub" type="submit" value="Submit!" />
</form>
</body>
<script type="text/javascript">
var div = document.getElementById('formSub');
function replaceWords(event) {
//Prevent form submission to server
event.preventDefault();
var commentContent = document.getElementById('comments');
var badWords = ["x", "y", "z"];
var censored = censore(commentContent.value, badWords);
}
function censore(string, filters) {
// "i" is to ignore case and "g" for global "|" for OR match
var regex = new RegExp(filters.join("|"), "gi");
return string.replace(regex, function (match) {
//replace each letter with a star
var stars = '';
for (var i = 0; i < match.length; i++) {
stars += '*';
}
return stars;
});
}
div.addEventListener('click',replaceWords);
</script>
</html>
<html>
<head>
<title>Syntax Highlighting</title>
</head>
<body>
<form name="badwords" method="post" action="" >
<textarea id="pesho" name="comments" rows="10" cols="60"></textarea>
<br />
<input id="formSub" type="submit" value="Submit!" />
</form>
</body>
<script type="text/javascript">
var div = document.getElementById('formSub');
function replaceWords(event) {
//Prevent form submission to server
event.preventDefault();
var commentContent = document.getElementById('pesho');
var badWords = ["crap", "fuck", "cunt"];
console.log(commentContent.value)
commentContent.value =censore(commentContent.value, badWords);
}
function censore(string, filters) {
console.log('in')
// "i" is to ignore case and "g" for global "|" for OR match
var regex = new RegExp(filters.join("|"), "gi");
return string.replace(regex, function (match) {
//replace each letter with a star
var stars = '';
for (var i = 0; i < match.length; i++) {
stars += '*';
}
return stars;
});
}
div.addEventListener('click',replaceWords);
</script>
</html>
As some of the other guys before me mentioned, you were not targeting the id of the text area but the name attribute, beside that for the function to make actual changes on the view you must change the targeted element value (see the modified example)

<input type=“text” maxlength=“4”> should not count comma and dot in maxlength

I have input field which contains number and special characters e.g. comma and dot
while calulating the maxLength of the field i want to skip special characters .
I dont want to restrict the special character.
Expected Output should be :- 1,234 (Total Length :- 4)
<form action="/action_page.php">
Username: <input type="text" maxlength="3" id="myId"/>
<input type="submit" value="Submit">
</form>
jsfiddle link here
Try adding this javascript:
window.onload = function() {
var textInput = document.getElementById("myId");
textInput.oninput = function() {
var temp;
temp = this.value.replace(/[^\w\s]/gi,'');
if (temp.length > 3) {
alert("Invalid"); // Or other stuff you want to do
}
};
};
Note that this code checks input on real time
This should be done with javascript:
var input = document.getElementById('myId');
input.addEventListener('keyup', function () {
// Checking length of string ignoring all non-digit and non-letter characters
if (this.value.replace(/[^\d|[^a-zA-Z]]*/g, '').length == 3) {
console.log('stop and do whatever you need')
}
})
You can try to use HTML5 pattern attribute. Just instead of maxlength type pattern and give it some regex. Could do something like this:
<form action="/action_page.php">
Username: <input type="text" pattern="(?(?=^.\d{1,3},\d{1,3}$)^.{5}$|^.{4}$)" id="myId"/>
<input type="submit" value="Submit">
</form>

jQuery replace integer globally in html var

I am trying to replace a number globally in my HTML string by regex but it only replaces the number when it's not attached to an attribute.
e.g. I want to replace the number 123 globally. The problem in this example is that only the number in the value has been changed and not the number between the brackets.
var oldId = 123;
var newId = 1234;
<input type="hidden" name="field_name" value="123">
<input type="radio" name="field_name[123]" class="id_123">
$('.settings').replace(/oldId/g, newId);
Current result
<input type="hidden" name="field_name" value="1234"> <-- changed
<input type="radio" name="field_name[123]" class="id_123"> <--- not changed
I guess I need to modify my regex a somehow?
You can use .each(), g flag at RegExp to replace .outerHTML of elements where name attribute includes "field_name"
var oldId = 123;
var newId = 1234;
$("input[name*=field_name]").each(function(i, el) {
el.outerHTML = el.outerHTML.replace(new RegExp(oldId, "g"), newId)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="field_name" value="123">
<input type="radio" name="field_name[123]" class="id_123">

Categories

Resources