Regex number filtering from textarea - javascript

I have been looking for way how I could filter data within textarea using regex function for a quite a while now without any success. Below is the regex I want to use to filter UK telephone numbers.
(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?
Fiddle: https://jsfiddle.net/qdypo04y/
I want to achieve the result when the button is clicked it will remove lines which do not meet the regex? Alternatively would remove values which are not UK telephone numbers.
Any guidance would be appreciated.

Apart the use of textarea element your issue is:
how attach click event listener to your button (refer to: querySelector and addEventListener)
how get the content of textarea and split it into rows (refer to: textContent plus split and join)
finally how use your regex: refer to test
An example is:
document.querySelector('button').addEventListener('click', function(e) {
var txtArea = document.querySelector('textarea[rows="4"][cols="50"]');
var re = /(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?/;
var txtArr = txtArea.textContent.split('\n');
txtArr.forEach(function(ele, idx) {
txtArr[idx] = ele + ' test result is: ' + re.test(ele);
});
txtArea.textContent = txtArr.join('\n');
});
<textarea rows="4" cols="50">
+447222555555
0800 042 0213
2017/07/14
2017/07/17
2017/07/27
</textarea>
<button>Click me</button>

<script>
function myFunction() {
var regexp = /(((\+44\s?\d{4}|\(?0\d{4}\)?)\s?\d{3}\s?\d{3})|((\+44\s?\d{3}|\(?0\d{3}\)?)\s?\d{3}\s?\d{4})|((\+44\s?\d{2}|\(?0\d{2}\)?)\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?/;
var content=$.trim($("textarea").val()).split('\n');
var result="";
for(var i = 0;i < content.length;i++){
if(regexp.test(content[i])){
result=result+content[i]+'\n';
}
}
$("textarea").val(result);
}
</script>
used JQuery to take the value from textarea

Related

Replace space with character in a string except for words between quotes with JQuery

In my web application I implemented a search functionality with a textbox and buttons with a jQuery onclick event handler attached. Each button triggers a different search handler.
HTML
<input id="searchText" placeholder="What are you looking for?" type="text" />
<div id="searchLinksBar">
All
Downloads
Knowledge Base
</div>
jQuery
"use strict";
$(document).ready(function() {
$("#searchLinksBar a").click(function() {
//Get content from the selected anchor
var categoryURL = $(this).attr("href");
//Get search string
var searchText = $("#searchText").val();
var searchString = ToQueryString(searchText);
//Check if the search bar is filled
if(searchString.trim()){
categoryURL = categoryURL + "&str="
}
//Attach the two strings to get our full URL
var searchUrl = categoryURL + searchString;
window.location.href = searchUrl;
return false;
})
});
function ToQueryString(text) {
return text.replace(/ /g, "+");
}
The search works great except when a user wants to search an exact phrase by including several words within quotes. There shouldn't be the '+' sign between words within quotes, otherwise the handler does not work as expected. I might think of a solution by using regular expressions or use the concat and split function (see below) to divide words within quotes from those with quotes and place in a array but maybe there is a more elegant solution
var phrases = [].concat.apply([], text.split('"').map(function(v,i){
return i%2 ? '"'+v+'"' : v.split(' ')
})).filter(Boolean);

How to display <input type=''text'> without creating a textbox in jquery?

I have a comment box(textarea) in which the user types something and when he hits enter that thing is automatically displayed in 'comment section'. Now when the user hits submit I'm executing the following code,
var comment = $("#commentBox").val();
var commentSection = $("#commentSection");
comment.appendTo(commentSection);
By the above code the comment typed by user is dynamically displayed in the commentSection. This works fine but when user types something like,
<input type='text'>
in the comment box then a textbox is created within the comment section. So is there a way through which I could not let this happen?
Thanks in advance.
One way would be to just append the data as .text
Something like this:
var comment = $("#commentBox").val();
var commentSection = $("#commentSection");
commentSection.text(comment);
Edit: To append to an existing part of the comment, replace:
commentSection.text(comment);
with:
commentSection.text(commentSection.text() + comment);
You have to convert the string to entities. Define this function:
function htmlencode(str) {
return str.replace(/[&<>"']/g, function($0) {
return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
});
}
Then run the following code when the user hits enter:
var comment = htmlencode($("#commentBox").val());
var commentSection = $("#commentSection");
comment.appendTo(commentSection);
Try this ,
div.insertAdjacentHTML( 'beforeend', comment);
You can use
var commentText = $("#commentBox").text();
but this do not clean html tags on your string, additionally you can use a function to do this
function RemoveHTMLTags(vals) {
var regX = /(<([^>]+)>)/ig;
var html = vals;
return (html.replace(regX, ""));
}
and then you use:
var finalComment = RemoveHTMLTags(commentText);

Remove HTML tags from a javascript string

I have this code :
var content = "<p>Dear sms,</p><p>This is a test notification for push message from center II.</p>";
and I want to remove all <p> and </p> tags from the above string. Just want to display the string values without html tags like :
"Dear sms, This is a test notification for push message from center II."
Why not just let jQuery do it?
var content = "<p>Dear sms,</p><p>This is a test notification for push message from center II.</p>";
var text = $(content).text();
Here is my solution ,
function removeTags(){
var txt = document.getElementById('myString').value;
var rex = /(<([^>]+)>)/ig;
alert(txt.replace(rex , ""));
}
Using plain javascript :
content = content.replace(/(<p>|<\/p>)/g, "");
You can use jQuery text() to get plain text without html tags.
Live Demo
withoutP = $(content).text()
var content = "a<br />";
var withoutP = $(content).text()
alert(withoutP )
This one does not work for the .text() solution.
this one is checking for special chars
var $string = '<a href="link">aaa</a>';
var $string2 = 'aaa';
var $string3 = 'BBBBB';
var $string4 = 'partial<script';
var $string5 = 'has spaces';
function StripTags(string) {
var decoded_string = $("<div/>").html(string).text();
return $("<div/>").html(decoded_string).text();
}
console.log(StripTags($string));
console.log(StripTags($string2));
console.log(StripTags($string3));
console.log(StripTags($string4));
console.log(StripTags($string5));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
myString.replace(/<[^>]*>?/gm, '');
Place hidden element in markup, or create it from jQuery. Use this code to get plain text without complications with incomplete tags, < etc.
content = $(hiddenElement).html($(hiddenElement).html(content).text()).text();
Above approch is not working for me. so i got one alternative solution to solve this issue`
var regex = "/<(.|\n)*?>/";
var originaltext = "1. Males and females were compared in terms of time management ability. <br><br>The independent variables were the people in the study.<br><br> Is this statement correct";
var resultText = body.replace(regex, "");
console.log(result);
Use regex:
var cleanContent = content.replace(/(<([^>]+)>)/ig,"");
you can use striptags module to remove HTML and get the text. It's quite an easy and straightforward solution.
function htmlTagremove(text) {
var cont = document.createElement('div'),
cont.innerHTML=text;
return $(cont).text();
}
htmlTagremove('<p><html>test');

Replace the contents of a div with regex match of string

I'm trying to figure out how to replace the contents of a <div> with the results from a regex .match() statement on a string. This is the code I have so far but I can't get it to work. I want the button to stay on screen but the <div> to reflect the matched word.
<html>
<body>
<script type="text/javascript">
function search(){
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.write(str.replace(document.getElementById("results"),
(str.match(patt1))));
}
</script>
</body>
<div id="results">So this is some text.</div>
<button name="Search" onclick="search()">Click Here</button>
</html>
Any ideas as to why it's not working?
You need to stop the button completing it's default event, which is to submit the page. (Edit: No it's not, its default event is nothing - assumed it was a <submit> :) )
In addition, to get a div from the document basic on it's id attribute, you use document.getElementById('id-of-element') and to set the contents of a div, you use .innerHTML on the element we just got.
// We need to take the event handler as a parameter for the function, let's call it e
function search(e){
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.getElementById("results").innerHTML = str.match(patt1)[0];
// This line stops the default action occurring
e.preventDefault();
}
Note: we don't need to specify an argument here, e goes in automatically
<button name="Search" onclick="search()">Click Here</button>
Your code is searching for the String "So this is come text." in the String "Visit W3Schools" and replacing it with the array ["W3Schools"], then writing it to the screen. This doesn't make much sense.
Try something like this instead:
function search(){
var str = "Visit W3Schools";
var patt1=/w3schools/i;
document.getElementById("results").innerHTML=(str.match(patt1))[0];
}
document.write will replace the entire page with the passed in parameter. So you just want to update that single DIV, results. So you want to use innerHTML:
function search() {
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
document.getElementById("results").innerHTML = str.match(patt1)[0];
}

Javascript functions

So I have a textbox which allows a max entry of 5 characters.
The user should enter the time in the format hh:mm or hhmm , into the textbox.
Supposing the user enters 1:2:3 or 1::2 etc, then it should show an alert message('Incorrect time format')
Is there any way I can check all other occurences of : EXCEPT for the first : , and alert the user?
(This needs to be done within a javascript function)
This is what I used to check for non-digit values(excluding :) entered into textbox:
<script type='text/javascript'>
function getClks(){
...
var re=":";
var found = clks.match(re);
if (clks.match(/^[0-9:]/)){
alert('Invalid time value');
}
if (found=:){
var splitime = clks.split(":");
var hours = splitime[0];
var mins = splitime[1];
......
}
}
</script>
Unless you have a very good reason to change the user's input. I would recommend only alerting the user that their input doesn't match the correct format.
If you really want to remove characters, you can use the replace function with some regex to remove the extra : chars.
You can use search or match to test whether the input is in the correct format.
Something like /^\d{1,2}:\d{2}$/ should work.
try to use this jquery plugin: http://digitalbush.com/projects/masked-input-plugin/
It will mask your textbox:
$("#hour").mask("99:99");
#alexl's jQuery plugin is probably enough, but for completeness sake..
Outside jQuery contexts I'd use a RegExp, /([0-9][0-9]):([0-9][0-9])/, and test the number string like so:
var timestr = /* .. get the text .. */
if(timestr.match(/([0-9][0-9]):([0-9][0-9])/) {
console.log('Good number string');
} else {
console.log('Bad number string');
}
Everyone else explained what to do. Here's a more concrete example of how to use it.
var regex = new RegExp("\\d{2}[:]\\d{2}");
if (regex.test(input)) {
var array = input.split(":");
var hours = array[0];
var minutes = array[1];
} else {
alert("malformed input");
}
You could do something like this
markup
<input id="myinput" maxlength="5" type="text" />
<input type="button" onclick="test()" value="test" id="testbtn" />
js
var re = new RegExp("^([0-1][0-9]|[2][0-3])(:([0-5][0-9])){1,2}$");
var myInput = document.getElementById('myinput');
function test(){
alert(re.test(myInput.value)); //alerts true if the input is well-formed
}
example => http://jsfiddle.net/steweb/rRZLx/

Categories

Resources