How to case insensitive search regex - javascript

So I have this search, example I have this in my table "Test Building" and I can only search the first part of the name and its case sensitive like I input Test but I cant search if I type Building which is my problem so how do I correct this? here's what I did..
building.blade.php
<center>
<div class="input-group col-xs-4 col-md-6" >
<input type="text" name="search" id="search-building" class="form-control" placeholder="Search..." required>
<span class="input-group-btn">
</span>
</div>
</center>
<script type="text/javascript">
$("body").on("input", "#search-building", function() {
var text_filter = $(this).val();
var tr = $('tr');
$("table").find("tbody").find("tr").hide();
$("table").find("td").show();
$("table").find("tbody").find("tr:contains("+text_filter+")").show();
});
</script>

You could try:
var text_filter = $(this).val().toLowerCase()
Then it will always be lowercase.

I'm not sure if there's a nice jQuery-ish way to do that, but here's what I thought about.
You want a simple thing: find all trs in your table's body that contain some text. Text should be treated case-insensitively, so the tr:contains(...) doesn't work for you. There's nothing on the documentation saying we can make it case insensitive. So let's implement our own version!
It's quite simple: instead of using find, you want to get a list of all children of your tbody element and then filter them (which means you will take out those don't match the criteria). The criterion will be a case-insensitive RegExp.
Instead of this line:
$("table").find("tbody").find("tr:contains("+text_filter+")").show();`
Try doing this:
function matchesText (index, element) {
const regexp = new RegExp(text_filter, 'i')
return element.text().match(regexp)
}
$("table").find("tbody").children().filter(matchesText)
If you're not familiar with filter, please read about it here. It is a very ubiquitous concept now, when people heavily use functional programming.
I haven't tested this but it should work. The essence is creating a new regexp passing it the text and 'i' flag, which means "become case-insensitive". If you don't know how regular expressions work, please search the internet for it. Here we don't use any of complex concepts from RegExp world.
Again, we could do the same by just matching the case of both strings. Say, making both of them lowercase, like that: text_filter.toLowerCase().

Related

Replace part of a string with another string 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

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.

JavaScript RegExp #hasgtag replace into link without hyper hashlink in html

I want to replace #hashtag text into something #hasgtag with JavaScript or jQuery
Here I tried:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit #Microsoft! #facebook Somelink
</p>
<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var txt = str.replace(/#\w+\.?\w+/g,"#Selected ");
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
But This result returned...
<p id="demo">Please visit #Selected ! #Selected #Selected "> Somelink
</p>
I want to result be like
<p id="demo">Please visit #Microsoft ! #facebook Somelink
</p>
Wow! This was a surprisingly difficult problem, although it seems like it should be simple at first glance.
The problem is that, strictly speaking, your requirement demands that only text nodes be processed to transform hashtags into links. Existing HTML should not be touched at all.
A naïve approach (seen in the other answers) would attempt to devise a complex regular expression to dodge the HTML. Although this may appear to work for some cases, even nearly all practical cases, it is absolutely not foolproof. Regular expressions are simply not powerful enough to fully parse HTML; it is just too complex a language. See the excellent and rather famous Stack Overflow answer at RegEx match open tags except XHTML self-contained tags. It can't be done perfectly, and should never be done at all.
Rather, the correct approach is to traverse the HTML tree using a recursive JavaScript function, and replace all target text nodes with processed versions of themselves, which, importantly, may involve the introduction of (non-text) HTML markup inside the text node.
jQuery can be used to accomplish this with minimal complexity, although the task itself necessitates a certain amount of complexity, which, honestly, can't be avoided. As I said, this is a surprisingly difficult problem.
HTML
<button onclick="tryItClick()">Try it</button>
<p id="demo">Please visit #Microsoft! #facebook Somelink
</p>
JavaScript
if (!window.Node) {
window.Node = {
ELEMENT_NODE : 1,
ATTRIBUTE_NODE : 2,
TEXT_NODE : 3,
CDATA_SECTION_NODE : 4,
ENTITY_REFERENCE_NODE : 5,
ENTITY_NODE : 6,
PROCESSING_INSTRUCTION_NODE : 7,
COMMENT_NODE : 8,
DOCUMENT_NODE : 9,
DOCUMENT_TYPE_NODE : 10,
DOCUMENT_FRAGMENT_NODE : 11,
NOTATION_NODE : 12
};
} // end if
window.linkify = function($textNode) {
$textNode.replaceWith($textNode.text().replace(/#(\w+\.?\w+)/g,'#$1'));
}; // end linkify()
window.processByNodeType = function($cur, nodeTypes, callback, payload ) {
if (!nodeTypes.length)
nodeTypes = [nodeTypes];
for (var i = 0; i < $cur.length; ++i) {
if ($.inArray($cur.get(i).nodeType, nodeTypes ) >= 0)
callback($cur.eq(i), $cur, i, payload );
processByNodeType($cur.eq(i).contents(), nodeTypes, callback, payload );
} // end for
} // end processByNodeType()
window.tryItClick = function(ev) {
var $top = $('#demo');
processByNodeType($top, Node.TEXT_NODE, linkify );
}; // end tryItClick()
http://jsfiddle.net/3u6jt988/
It's always good to write general code where possible, to maximize reusability, and often simplicity (although too much generality can lead to excessive complexity; there's a tradeoff there). I wrote processByNodeType() to be a very general function that uses jQuery to traverse a subtree of the HTML node tree, starting from a given top node and working its way down. The purpose of the function is to do one thing and one thing only: to call the given callback() function for all nodes encountered during the traversal that have nodeType equal to one of the whitelisted values given in nodeTypes. That's why I included an enumeration of node type constants at the top of the code; see http://code.stephenmorley.org/javascript/dom-nodetype-constants/.
This function is powerful enough to be called once in response to the click event, passing it the #demo element as the top node, whitelisting only Node.TEXT_NODE nodes, and providing linkify() as the callback.
When linkify() is called, it just takes its first argument, which is the node itself, and does the exact replacement you devised (although capture group backreferences had to be added to properly replace the text with the hashtag). The last piece of the puzzle was to replace the text node with whatever new node structure is needed to effect the replacement, which, if there was indeed a hashtag to replace, would involve the introduction of new HTML structure over the old plain text node. Fortunately, jQuery, whose awesomeness knows no bounds, makes this so incredibly easy that it can be accomplished with a sweet one-liner:
$textNode.replaceWith($textNode.text().replace(/#(\w+\.?\w+)/g,'#$1'));
As you can see, a single call to text() gets the text content of the plain text node, then the replace() function on the string object is called to replace any hashtag with HTML, and then jQuery's replaceWith() method allows us to replace the whole text node with the generated HTML, or leave the original plain text in place if no substitution was performed.
References
http://blog.alexanderdickson.com/javascript-replacing-text
http://api.jquery.com/children/
http://code.stephenmorley.org/javascript/dom-nodetype-constants/
http://api.jquery.com/replacewith/
RegEx match open tags except XHTML self-contained tags
You have to capture the text with parenthesis, but have also to capture just the text, not what is in the html tags. See comments in the function.
function hashtagReplace() {
var text = document.getElementById("demo").innerHTML;
//you have first to capture the text, to avoid the capture of #link in your example
//The text is somewhare between the start of the input, or ">" and the end of the input and "<"
var result = text.replace( /(^.|>)([^<]*)(<|.$)/g ,function(match, start, capture, end ){
//then you capture the hashtag text, and replace all the hashtag (#+hashtag_word) by the link.
//you set the text captured by the parentethis with $1
var hashtagsReplaced= (start+capture+end).replace(/\#(\w+)/g,"#$1")
//you return all the html
return hashtagsReplaced;
});
//finally you replace the html in the document
document.getElementById("demo").innerHTML = result;
}
<!DOCTYPE html>
<html>
<body>
<button onclick="hashtagReplace()">Try it</button>
<p id="demo">#Microsoft Please visit #Microsoft ! #facebook Somelink
</p>
</body>
</html>
You need to capture the group and then use it in the replace. Something like:
var txt = str.replace(/#(\w+\.?\w+)/g,"#$1 ");
Putting brackets around the part you want to capture makes it a capture group and then the captured group will be inserted at the $1 token in the replacement string.
Of course, your bigger problem is that your regex matches your existing link and tries to substitute in there too, which completely messes things up. This is why it's not a great idea to use a regex to parse HTML. You could work on your regex to exclude existing links, but that quickly becomes a headache. Use DOM manipulation instead.
You could just change your regex to:
/\s(?!href=")#(\w+\.?\w+)/g
Which takes advantage of the fact that the #link in your existing link isn't proceeded by a space. So you get something like this:
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var txt = str.replace(/\s(?!href=")#(\S+)/g, " #$1 ");
document.getElementById("demo").innerHTML = txt;
}
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit #Microsoft! #facebook
Somelink
</p>

Trying to use element ID to access object values native javascript

I'm trying to write some code to validate a form. I only want to use native js (ie no jQuery etc) and in addition I want to steer clear of inline events.
The (simplified version of the) form looks as follows:
<body onload="addListener()">
<div class="center">
<form method="get" name="signUpForm">
<input type="text" id="firstName"><br />
<input type="text" id="lastName"><br />
<input type="text" id="age"><br />
<input type="submit" value="Submit">
</form>
</div>
What I've then done is created an object to contain relevant information as it pertains to each field (have just added the initial one here to give you the idea:
var Field = { req: true,
minlength: 2,
maxlength: 20,
errorMessage: "",
regex: /[^a-zA-Z- ]/}
var firstName = Object.create(Field);
firstName.maxlength = 30;
firstName.errorMessage = "Please enter a first name between one and twenty letters. Please use only uppercase and lowercase letters spaces and hyphens.";
firstName.regex = /[^a-zA-Z- ]/;
What I now want to do is use the id of the field which triggers the event to access the information contained in the Field object.
The two very simple functions I've written thus far tom attempt this are:
function addListener(){
document.body.addEventListener('keyup', eventIdentify);
}
function eventIdentify(){
var target = event.target || event.srcElement;
var id = target.id
console.log(id.maxlength);
}
However and this where it becomes a bit of a nightmare, id.maxlength keeps returning undefined.
If I try it with: "console.log(firstName.maxlength);" then it's fine but obviously that defeats the point. Not sure what's going on here, I suspect it's something to do with the id being used to reference two different things (the element id and the object) but I'm pretty new to this and not sure.
Would gratefully appreciate it if someone couold point me in the right direction.
Thanks in advance
Stef
target.id is a string, and as such it does not have a maxlength property. A quick solution would be to access de variable that is named as your id:
console.log(window[target.id].maxlength)
Still, a better way would be to create an object and incluse the other objects you already have:
var obj={};
obj.firstName=firstName;
And then you can do:
console.log(obj[target.id].maxlength)

find text wrapped in brackets in jQuery

I have some text on a page and I want to located and remove any text found in brackets.
For example:
<td>here is [my text] that I want to look at</td>
So I want to grab that text (my text), save it in a variable and remove it from where it is.
If you're using jQuery you could use a regular expression like \[(.+)\] on $('body').text().
EDIT: Sorry, I might have jumped the gun a little bit giving you this answer. Going to think about it for a few more minutes and try to update this with a little more info.
You may find that this task is not all that simple. If you have control over the text before it is sent to the web browser you may want to put a <span class='bracket'>[my text]</span> around the text, then you could easily do something like this with jQuery:
$(".bracket").each(function() {
// store the data from $(this).text();
}).remove();
This can be done using regular expressions and jQuery, but there are problems that may creep up dealing with text inside of attributes like <input name='test[one][]' /> The "simple" regex would be to do something like this:
$("td").each(function() {
var $this = $(this);
var html = $this.html();
var bracketText = [];
// match all bracketed text in the html - replace with an empty string
// but push the text on to the array.
html = html.replace(/\[([^\]]+)\]/g, function() {
bracketText.push(arguments[1]);
return "";
});
// put the new html in away and save the data for later
$this.html(html).data("bracketText", bracketText);
});
There is not much danger in doing this if you're sure you wont have [] inside of tags other than in the text.
I ended up doing the following:
$('#formQuizAnswers td.question').each(function(){
var header = $(this).text().match(/-.*-/);
$(this).text($(this).text().replace(header,''));
});
I changed my text I search for to have dashes around it IE -My text-

Categories

Resources