I'm trying to write a regex script that will parse through HTML name attributes and return each nested array as a match. Here's an example:
<input type="text" name="contact[email]" />
<input type="text" name="contact[address][street]" />
I need some javascript regex that will parse those and match them in this way
Match 1: contact Match 2: email
Match 1: contact Match 2: address Match 3: street
Here's the current regex I have:
/(^.*?)(\[(.*?)\])?$/
Thanks!
I think the easiest way to do this is
var str = "contact[email]"
str.match(/\w+/g)
//=> ["contact", "email"]
var str = "contact[address][street]"
str.match(/\w+/g)
//=> ["contact", "address", "street"]
What I would do is delimit each of your name with []
So it would go like this:
<input type="text" name="[contact][email]" />
<input type="text" name="[contact][address][street]" />
Then I would use this for the regex:
(?:\[)(.*?)(?:\])
My solution cuts down on the number of operations needed and makes your naming convention a lot more straight forward. Each match would represent a separate entry in the name section
Use the following regex:
/(^[^\[]+)(?=\[)|(([^\[\]]+)(?=\]))/g
Example usage below.
Demo fiddle here.
HTML:
<input id="one" type="text" name="contact[email]" />
<input id="two" type="text" name="contact[address][street]" />
JavaScript:
var regex = /(^[^\[]+)(?=\[)|(([^\[\]]+)(?=\]))/g;
var nameOne = document.getElementById('one').getAttribute('name');
console.log('one: ', nameOne.match(regex));
var nameTwo = document.getElementById('two').name;
console.log('two: ',nameTwo.match(regex));
Output:
one: ["contact", "email"]
two: ["contact", "address", "street"]
<input type="(?<type>[A-Za-z0-9]+)" name="(?<Name>[A-Za-z0-9\[\]]+)" />
works fine. I attached Image to show how works
as each value will be returned in array after RegexMatch,
then you can do this
var first = RegexMatch.Groups["Name"].Split('[')[0];
You will get the first value in the name="contact[address][street]", first = "contact"
then you can do
var second = regexMatch.Groups["Name"].Split('[')[1];
then second = "address";
by the way this is for C#, convert to javascript!!
i like to use split() to grab middle-chunks instead of more complex RegExps:
var strFormHTML='<input type="text" name="contact[email]" /><input type="text" name="contact[address][street]" />';
var names = strFormHTML.split(/[\W\w]+? name=\"([^"]+)\"[\w\W]+?/).filter(Boolean).slice(0,-1);
alert(names); //shows: "contact[email]", "contact[address][street]"
Related
here i have two input field as like
$(document).ready(function() {
$("#business_name").keyup(function() {
var Text = $(this).val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
$("#business_url").val(Text);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="business_name" name="business_name" placeholder="Business Name" />
<br><br>
<input type="text" id="business_url" name="business_url" placeholder="Business URL" />
now I want if someone wrote : My Business Name on first input field then 2nd field it will be write mybusiness thats it but now it showed my-business-name i dont want this (I need only two word if it will take longer name then it only shows first two word thats it )
To get only the first two words you can split() the string in to an array by spaces and then use slice() to get the first two elements of the resulting array. Then you can join it back together before displaying in the input.
Also note I added trim() and a regex to replace multiple whitespace with a single one, otherwise it would affect how split() builds the array and could end up missing words.
jQuery($ => {
$("#business_name").on('input', e => {
var text = $(e.target).val().trim().replace(/\s+/, ' ').toLowerCase().split(' ').slice(0, 2).join('');
$("#business_url").val(text);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="business_name" name="business_name" placeholder="Business Name" /><br /><br />
<input type="text" id="business_url" name="business_url" placeholder="Business URL" />
After replacing certain characters with ' ' count the number of ' ' in the string. If the count is 2 stop replacing or you can return from the function.
Look at the modified code below:
$(document).ready(function() {
var count = 0;
$("#business_name").keyup(function() {
var Text = $(this).val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-zA-Z0-9]+/g,' ');
count = (Text.split("-")).length - 1;
if (count == 2) {
return;
}
$("#business_url").val(Text);
});
});
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>
I have this line:
first (word1-word2-word3) second (any1-any2-any3)
Lets say I have a textarea and two inputs (input1 and input2).
When I paste the line above inside the textarea, and by using JavaScript, I want:
word1-word2-word3
to go to the first input (input1) and for the other part;
any1-any2-any3
to go to the second input (input2).
Thank you.
You could use a regular expression and take the two matching groups.
function split(v) {
var m = v.match(/^.*\((.*)\).*\((.*)\)$/);
document.getElementById('input1').value = m[1];
document.getElementById('input2').value = m[2];
}
<textarea onchange="split(this.value)"></textarea><br>
<input type="text" id="input1"><br>
<input type="text" id="input2">
Hello very smart people of the internet. I have a question that I can't seem to get right. I have three textboxes in a form, which represent 3 different parts of a phone number. Here is the code for them.
<form name="addacell" method="post" action="<?=$_SERVER['PHP_SELF'];?>">
<input type="text" value="" maxlength="3" name="phoneNumber" id="addcell1"/ size="1" placeholder="XXX">
<input type="text" value="" maxlength="3" name="phoneNumber" id="addcell2" size="1"/ placeholder="XXX">
<input type="text" value="" maxlength="4" name="phoneNumber" id="addcell3" size="2" placeholder="XXXX"/>
Next, I am submitting the form and running some validation to check if it meets the phone requirements I have set up for it. (Ignore validation I am not dealing with it until I get everything else straightened out)
<input type="submit" name="submitcell" value="Add" id="submitcell" class="sm-button" onclick="return validatePhone(document.addacell.addcell);"/>
Here is what I need help with: I need to put these 3 individual parts of the phone number together, store it as XXXXXXXXXX in a variable, display it as (XXX)XXX-XXXX and then award you with a huge internet hug.
Thanks in advance for all your hard work for me!!!
First of all: don't name all the separate parts of the phone number the same thing.
Try phone1, phone2 and phone3 in the name attribute of each input.
In your PHP code, something simple as:
$phone1 = $_POST['phone1'];
$phone2 = $_POST['phone2'];
$phone3 = $_POST['phone3'];
// store
$store = $phone1.$phone2.$phone3; // do whatever you want with this
// display
$display = "(".$phone1.")".$phone2."-".$phone3;
Also, there seems to be some misplaced "/" in your code. Check that.
First, rename your inputs. They're all called 'phoneNumber'.
Then call something like $sPhoneNumber = $_POST['phoneNumber1'] . '-' . $_POST['phoneNumber2'] . '-' . $_POST['phoneNumber3'];
The variable $sPhoneNumber now contains the input from the 3 fields (renamed to phoneNumber1, phoneNumber 2 and phoneNumber3).
Using some basic Javascript you can build the strings you are looking for.
var text1 = document.getElementById(addcell1).value;
var text2 = document.getElementById(addcell2).value;
var text3 = document.getElementById(addcell3).value;
var storeText = text1 + text2 + text3;
var displayText = "(" + text1 + ")" + text2 + "-" + text3;
How do I compare similar strings in jquery?
<script src="../../js/jq.js"></script>
<script>
$(function(){
var str1 = $.trim($('#str1').val().toUpperCase());
var str2 = $.trim($('#str2').val().toUpperCase());
if(str1==str2){
console.log('yep');
}
});
</script>
<input type="text" id="str1" value="One String"/>
<input type="text" id="str2" value="One String1"/>
Comparing "One String" and "One String1" is not going to work if I'm only checking if the two values are equal. Is there any way to do this in jquery? For example I only want to compare 90% of the string.
You can see if one is contained inside the other for example:
if (str1.indexOf(str2) >= 0 || str2.indexOf(str1) >= 0)
console.log('yep');
}
Check this out : http://jsfiddle.net/Sj5dE/ You can comment out a,b block to see the similitude of the strings. It's of course case-sensitive. I hope this helps. Since your example talked about comparing two similar strings, I thought it'd be most likely that the beginning of the strings are the same so I didn't introduce any substring logic but feel free to change the function.
Try this it might work
<script src="../../js/jq.js"></script> <script>
$(function(){
var str1 = $.trim($('#str1').val().toUpperCase());
var str2 = $.trim($('#str2').val().toUpperCase());
if(str1===str2){ console.log('yep'); } });
</script>
<input type="text" id="str1" value="One String"/>
<input type="text" id="str2" value="One String1"/>
In javascript you can use the substring to get the 90% of the string you would like to compare.
$(function(){
var str1 = $.trim($('#str1').val().toUpperCase().substring(0, 10);
var str2 = $.trim($('#str2').val().toUpperCase().substring(0, 10);
if(str1==str2){
console.log('yep');
}
look on
http://code.google.com/p/google-diff-match-patch/
the demo in
http://neil.fraser.name/software/diff_match_patch/svn/trunk/demos/demo_diff.html
You can check if the string is present or not by
$(".className").replace(/(^|\s)yourTextHere\S+/g, " ");