Pass value to Regex - javascript

I am trying to make a function with regular expression [javascript].
Please take a look.
function ReplaceIt(key)
{
var KeyCode = /.body\s*\{([^\}]*?)\}/m; // i want to replace the body to the key
}
var key ="h1";
ReplaceIt(key);
so the final result will be
var Keycode = /.h1\s*\{([^\}]*?)\}/m;
I am little bit newbie with javascript and I don't know how to search other resources.
Note: Friends, why are you deleting the answers?? Each and every comment/answer is helping us to improve, but we will choose the most appropriate/best answer, please don't delete comments/answers.

You can use RegExp with a string to build up your regular expression. If you build the regular expression that way, you should escape all '\'. So your function could look like:
function ReplaceIt(key)
{
return RegExp('.'+key+'\\s*\\{([^\\}]*?)\\}','m');
}
var reKey = ReplaceIt('h1'); //=> /.h1\s*\{([^\}]*?)\}/m

Related

Replace specific words amongst page content with value javascript

I'm trying to replace the word hello anywhere on the page with the word hi using Javascript. I created the script below however it isn't working how anticipated, is there something that I can do to achieve the outcome desired.
function(data) {
var newdata = data.replace("hello", "hi");
}
Jsfiddle
This will work, although might be overkill using regular expressions:
document.body.innerHTML = document.body.innerHTML.replace(/hello/g, "hi")
Jsfiddle
In your example, you are only replacing the first occurence.
Below the JavaScript documentation about replace:
Note: If you are replacing a value (and not a regular expression),
only the first instance of the value will be replaced. To replace all
occurrences of a specified value, use the global (g) modifier.
You have to use the global modifier as below
function(data) {
var newdata = data.replace(/hello/g,"hi");
}

Escaping javascript entities in js?

I want to escape javascript entities on client side. For example :-
If my input string is tes"t result should be tes\"t
Is there any inbuilt function provided by jquery for this ?
This is a really crazy, almost stupid shot in the dark on my part, but...
If you're using a server-side language like PHP to output variables' contents into JavaScript, you should use json_encode as this handles ALL escaping for you, regardless of the type of variable.
On the other hand, if you're (I really hope you're not) doing something like this:
var input = "test"t";
And trying to escape that properly while in JavaScript... that's not going to work. It's a syntax error. You need to escape your literals manually.
Kevin van Zonneveld provide a JavaScript equivalent of PHP’s addslashes here :
http://phpjs.org/functions/addslashes/
function addslashes(str) {
// example 1: addslashes("kevin's birthday");
// returns 1: "kevin\\'s birthday"
return (str + '')
.replace(/[\\"']/g, '\\$&')
.replace(/\u0000/g, '\\0');
}
Based on this function, I guess you might want to add this function to prototype of the String like this.
if (!String.prototype.addslashes) {
String.prototype.addslashes = function () {
return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
};
}
var str = 'tes"t';
alert(str.addslashes()); // shows 'tes\"t'
DEMO: http://jsfiddle.net/naokiota/6F6aN/6/
Hope this helps.

Regular Expression in indexOf on javascript

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') + ')'))

How do I extract a substring from a string in Jquery

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.

JavaScript: dynamic regex for my own parser

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?

Categories

Resources