I want to write a message in a textarea and be able to refer to a person using the # symbol.
e.g
Please call #Larry David regarding
something
When submitting the form, I want to extract the persons name ie Larry David.
How do I go about extracting this string with Jquery?
What if the person name is Larry David Regarding? I think the best you can do here is to extract Larry:
var result = $('#textareaId').val().match(/\#(\w+)/);
if (result != null && result.length > 1) {
alert(result[1]);
}
Well to match what you asked for it would be:
var str = "Please call #Larry David regarding something";
var re = /#(\w+\s\w+)/;
var name = str.match(re);
if(name){
alert(name[1])
}
But it would fail for names like foo-bar, O'Donald, etc.
A regular expression such as
var re = /#(\w+\s[\w-']+)/;
would be a little better, but still will fail with other names.
Without a better way of figuring out where the name ends, you may have errors with names.
Related
I'm actually working on a website in which I'll need to replace many words by something like for example: banana by ******.
I use a website with php and mysql, but I also use javascript.
I have in my database a table in which are banned words.
I'm receive this words in an array from my database. i'm looking for a function that will be able to replace this words in all tha page. i can not use function like ob start.
The best will be a function that check on body onload and replace words.
This is a rather difficult task to tackle because:
People will try to circumvent this system by replacing certain letter, such as "s" with "$", "a" with "#", or by misspelling words that can still be understood
How will you deal with words like "password" that contains an swear word?
I would recommend going with a service that already has this figured out:
http://www.webpurify.com/
Look at this SO post: How do you implement a good profanity filter?
I'm going to use CoffeeScript, you can compile to JavaScript here if you wish or just use this as pseudocode.
String::replaceAll = (a, b) ->
regExp = new RegExp(a, "ig")
#replace regExp, b
_stars = (string) ->
str = ""
for i in [0..string.length]
str = "#{str}*"
str
bannedWords = [ "bannedword", "anotherbannedword" ]
_formSubmitHandler = (data) ->
for bannedWord in bannedWords
data.userInput = data.userInput.replaceAll bannedWord, _stars(data.userInput)
If the page content is as well coming from the database, or being entered into the database. Why not filter it using php prior to it being inserted or when it is pulled using str_replace
// PREFERRED WAY
$filteredContent = str_replace($bannedlist, "**", $content2Filter);
Or if you are looking for a javascript version, then you would need to use either multiple str.replace or regex. Something like:
var search = "/word1|word2|word3/gi"; //This would be your array joined by a pipe delimiter
var ret=str.replace(search,'**');
I made a very simple censoring method for this. It will only track words you put into the array of bad words. I would suggest you use an advanced library for word censors.
censor.js
var censor = (function() {
function convertToAsterisk(word) {
var asteriskSentence = '';
for(var asterisks=0;asterisks<word.length;asterisks++) {
asteriskSentence+='*';
}
return asteriskSentence;
}
return function(sentence, bannedWords) {
sentence = sentence || undefined;
bannedWords = bannedWords || undefined;
if(sentence!==undefined && bannedWords!==undefined) {
for(var word=0;word<bannedWords.length;word++) {
sentence = sentence.replace(bannedWords[word], convertToAsterisk(bannedWords[word]));
}
}
return sentence;
};
})();
The method can be used like so:
var sentence = 'I like apples, grapes, and peaches. My buddy likes pears';
var bannedWords = [
'pears',
'peaches',
'grapes',
'apples'
];
sentence = censor(sentence, bannedWords);
This system does not protect bad words within other words, or tricky mispellings. Only the basics.
var str="badword";
var ret=str.replace("badword","*******");
And to detect length automatically (useful for function useage)
var str="badword";
var ret=str.replace("badword",function() {
var ret = ""
for(var loop = 0; loop < str.length; loop++) {
var ret = ret + "*"
}
return ret
});
Finally I find my own way to make this system it is an easy way and you don't need to change all the code for all your website just the page that needs to be censored.
As far as I'm concerned I uses thausands of pages but the things is that I have one main page that included others pages.
For poeple who may be interested. all you have to do is to put this code at the beginning of your page so after the just put this code <?php ob_start(); ?> at the end of the body, before just put this code `
<?php
//We get the content of the page
$content = ob_get_contents();
// and we replace all
$content = str_replace('naughty', '*****', $content);
/// / VERY important, we must finish the page or in any case include ob_end_clean () function before echo $ content as PHP code would be displayed also
ob_end_clean ();
echo $content;
?>
This is an easy way, but you can also do an array for all censored words.
Full disclosure, I wrote the plugin.
I've written a jQuery plugin that does what you're looking for. It is not completely water tight, and others can very easily circumvent the plugin by disabling javascript. If you'd like to try it out, here's a link.
http://profanityfilter.chaseflorell.com/
And here's some example code.
<div id="someDiv">swears are ass, but passwords are ok</div>
<script>
$('#someDiv').profanityFilter({
customSwears: ['ass']
});
</script>
I want get my program parameters from rel attribute of element, first of all is it logical ?
and the rel attribute may contain this string rel="_p|b|w=300|h=200" or rel="_p|w=300"
, so I use split to split my string with | pattern :
var attr = $(this).attr('rel').split('|');
for _p and b there is no problem because I can check with indexOf but for w and h I should use regular expression because the w and h value will be change.
how can I use regular expression in indexOf ?
sorry for my bad English
EDIT:
if (attr.indexOf('b')) {
blank = true;
}
First of all, that isn't a very elegant way of retrieving data. Anyway, if you really want to do that in that way, then you can use regexes as follows:
var matches = $(this).attr('rel').match(/w=(\d+)/);
var w = (matches && matches[1]) || defaultValue;
Also, if there can be multiple elements that end in 'w', then you'd better change your regex to something like:
var matches = $(this).attr('rel').match(/(?:^|\|)w=(\d+)/);
I would have suggested the use of custom attributes as well, however these would not be w3-conform as you want them to.
A simple way would be to split the parameters and then loop through and check each index whether it is one of the attributes you are expecting:
var cust_params = $(this).attr('rel').split('|'); //or this.rel as GGG suggested in a comment?
for(var i=0;i<cust_params.length;i++) {
if('_p'==cust_params[i]) {
//...
}
//...
if(cust_params[i].match(/w=(\d+)/)) {
//you could even do this without a regular expression
}
}
I hope this doesn't violate some good practice that I'm unaware of because I always feel like there must be a more elegant way when I do this kind of thing :) As it is I get a kind of quick-and-dirty feel about this.
Sorry there is no way you can do it in one command with normal javascript, indexOf just doesn't support regular expression.
You can either loop through the array or use jquery supported command for array.
For example: once you have the array attr as you like, you can use jQuery.grep() http://api.jquery.com/jQuery.grep/
a_equal = jQuery.grep(attr, function(a, i){
return (a.match(/=/) and i > 0); // modify this as you like
});
to create an array a_equal with all the assignment argument.
disclaimer.. code not yet tested.
Like Paolo Bergantino I'd also suggest using data-attributes, or you could store the data in a JSON (again, in a data attribute) and parse that:
<a href="#" data-info='{"width": "300", "height": "200", "color": "#fff", "etc": "foo"}'>
var info = JSON.parse(a.getAttribute('data-info'));
Edit: replaced eval with Phrogz's suggestion.
(With eval: eval('(' + a.getAttribute('data-info') + ')'))
I have a search function, and would like to display the search term in the search input.
My url is: search-1.html?keyword=XXXXXX
How do I get this, and display it in an input?
Thank you in advance.
Use this:
http://ajaxcssblog.com/jquery/url-read-get-variables/
Take luck!
Oh and then you can use the following to display its value in an input field:
$("#inputId").val($.url.param("keyword"));
If it is just one key=value in the url you can use simple regex like this:
var theValueYouWant = window.location.href.match(/keyword=(.+)/)[1]
And set the value of an input like this
$('input').val(theValueYouWant)
If you want to parse the GET string more thoroughly, this function should do it...
gets = {};
$.each(location.search.replace(/^\?/,'').split('&'),function(k,v){
bits = v.split('=');
gets[bits[0]] = bits[1];
});
Regex solution:
var S = window.location.search; // "?keyword=..." etc.
var T = S.match(/^\?(?:[^\b]*&+)?keyword=([^&]*)/);
if (T)
T = T[1]
else
T = "no keywords found"
If multiple values are given for "keyword" (e.x. ?keyword=XXX&keyword=YYY), the regex will only find the first of these values (e.x. XXX). This regex works even if there are other variables in the query string.
jQuery-less solution:
<script type="text/javascript">
var $_GET=[],pairs=location.href.toString().substring(location.href.toString().indexOf("?")+1).split("&");for(key in pairs){pos=pairs[key].indexOf("=");$_GET[pairs[key].substring(0,pos)]=decodeURIComponent(pairs[key].substring(pos+1).replace(/\+/g," "))};
// Now just access with $_GET
// example...
keyword = $_GET["keyword"];
</script>
I need to rewrite a querysting using javascript.
First I check to see if the variable is present, if it is I want to replace it with a new search term. If it is not present then I just add the new variable
I'm able to get it to work with simple terms like hat, ufc hat
whitespaces are %20, so ufc hat is really ufc%20hat
I run into problem with terms like make-up, hat -baseball, coffee & tea, etc..
What is the proper regex for this?
Below is my code, which doesn't work.
var url = String(document.location).split('?');
querystring = url[1];
if(querystring.match(/gbn_keywords=/)!=null)
querystring=querystring.replace(/gbn_keywords=[a-zA-Z0-9%20.]+/,"gbn_keywords="+term);
else
querystring=querystring+"&gbn_keywords="+term;
No Regex needed. To get the query arguments, take everything after ?. Then, split the string by & to return each argument. Split again by = to get the arg name (right of =) and the value (left of =). Iterate through each argument, a rebuild the URL with each argument, excluding the one you don't want. You shouldn't run into problems here because ?, &, and - must be escaped if they are to be used in arguments. You also said you want to add the argument if it doesn't exist, so just set a variable to true, while you are iterating through each argument, if you find the argument. If you didn't append it to the end of the query string that you rebuilt.
location objects already have perfectly good properties like pathname, hostname etc. that give you the separate parts of a URL. Use the .search property instead of trying to hack the URL as a string (? may not only appear in that one place).
It's then a case of splitting on the & character (and maybe ; too if you want to be nice, as per HTML4 B2.2) and checking each parameter against the one you're looking for. For the general case this requires proper URL-decoding, as g%62n_keywords=... is a valid way of spelling the same parameter. On the way out naturally you will need to encode again, to stop & going on to the next parameter (as well as to include other invalid characters).
Here's a couple of utility functions you can use to cope with query string manipulation more easily. They convert between the ?... string as seen in location.search or link.search and a lookup Object mapping parameter names to arrays of values (since form-url-encoded queries can have multiple instances of the same parameter).
function queryToLookup(query) {
var lookup= {};
var params= query.slice(1).split(/[&;]/);
for (var i= 0; i<params.length; i++) {
var ix= params[i].indexOf('=');
if (ix!==-1) {
var name= decodeURIComponent(params[i].slice(0, ix));
var value= decodeURIComponent(params[i].slice(ix+1));
if (!(name in lookup))
lookup[name]= [];
lookup[name].push(value);
}
}
return lookup;
}
function lookupToQuery(lookup) {
var params= [];
for (var name in lookup)
for (var i= 0; i<lookup[name].length; i++)
params.push(encodeURIComponent(name)+'='+encodeURIComponent(lookup[name][i]));
return params.length===0? '' : '?'+params.join('&');
}
This makes the usage as simple as:
var lookup= queryToLookup(location.search);
lookup['gbn_keywords']= ['coffee & tea'];
var query= lookupToQuery(lookup);
& character is used to seperate key and value pairs in the querystring. So that you can match all the characters except for & by re-writing your code as follows:
querystring=querystring.replace(/gbn_keywords=[^&]+/,"gbn_keywords="+term);
[^&]+ matches one or more characters up to & or end of string. But if there may situations where the querystring data may look like ...?gbn_keywords= (no value) then a slight modification is needed to the above line:
querystring=querystring.replace(/gbn_keywords=[^&]*/,"gbn_keywords="+term);
Just change + to * so that the regex will match 0 or more characters. I think this is better.
Why don't you run a split on url[1] and than replace the value of the gbn_keywords in that new array?
And if you use a JavaScript Framework, there might be a handy function that does all that. In Prototype there is the function toQueryParams().
I am trying a new direction in Language Kits (or whatever you want to call those multi language text files with placeholders). Basically, I have text like this: Hello, my name is %0. Welcome to %1!. This would be my pText.
My pValues is an array whose values represent %0 and %1.
The following function should find %0 and replace it with pValues[0] and so on.
function _parseDialogMessage(pText, pValues) {
var result = pText;
for (var i=0; i<pValues.length; ++i) {
var regex = new RegExp('\%'+i, 'gi');
pText = pText.replace(regex, pValues[i]);
}
return result;
}
It all works except for the fact that it does not replace the placeholders %0 and %1. All Variables have the expected values but .replace doesn't seem to find my placeholders.
Any help?
Edit 1
Shame on me... -.-
You don't need "dynamic regex", since replace can take a function as argument:
function _parseDialogMessage(pText, pValues) {
return pText.replace(/%(\d+)/g, function (s, i) { return pValues[i]; });
}
(and you should return pText.)
You are returning the result variable which hold the initial values of the ptext parameter..
return the pText variable..
UUhm, you return result and not the replace pText
While you can't use any of their code unless you want to GPL your library, the manual for gnu's gettext covers the rationale behind a number of topics related to internationalization.
http://www.gnu.org/software/gettext/manual/gettext.html
edit : I know you're just looking for a magic regex, but it won't be enough.
easy example :
I have %n computers.
I have 1 computers.
Did you know arabic has a special tense for 2 things, and chinese no tense for the number of things referred to?