Javascript: how to pass found string.replace value to function? - javascript

When I have something like this:
var str = "0123";
var i = 0;
str.replace(/(\d)/g,function(s){i++;return s;}('$1'));
alert(i);
Why does "i" equal 1 and not 4?
Also, is it possible to pass the real value of $1 to a function (in this case 0,1,2,3) ?

When you use string.replace(rx,function) then the function is called with the following arguments:
The matched substring
Match1,2,3,4 etc (parenthesized substring matches)
The offset of the substring
The full string
You can read all about it here
In your case $1 equals Match1, so you can rewrite your code to the following and it should work as you desire:
var str = "0123";
var i = 0;
str.replace(/(\d)/g,function(s,m1){i++;return m1;});
alert(i);

The expression
function(s){i++;return s;}('$1')
Creates the function and immediately evaluates it, passing $1 as an argument. The str.replace method already receives a string as its second argument, not a function. I believe you want this:
str.replace(/(\d)/g,function(s){i++;return s;});

You are calling the function, which increments i once, and then returns the string '$1'.
To pass the value to a function, you can do:
str.replace(/\d/g, function (s) { /* do something with s */ });
However, it looks like you don't actually want to replace anything... you just want a count of the number of digits. If so, then replace is the wrong tool. Try:
i = str.match(/\d/g).length;

Related

how do I convert to string in js

I have a variable that takes a string and uses the ToLowerCase Function and I want to be able to use the charAt function for example
if (message.content.charAt(0) === '!'){
console.log('correct')
}
although that is a string and I have a variable named Text this is the Variable
var Text
Text = message.content.toLowerCase()
although there is no error in this I want to be able to use the charAt function so I need it to be converted to a string how would I do this?
You can use the toString() method, something like this: var text = message.content.toString().toLowerCase()
Or also var text = String(message.content).toLowerCase()

How to split data with square brackets while declaring parameter in json

I am passing some data from js file to handler which in turn gets result from SP. I have a parameter like ID = abc[123]. but i have to pass only 123 as value to ID to SP.
This is how im declaring parameter in js
var parameters = JSON.stringify({
"ID": JSON.stringify(EditedID).replace(/]|[[]/g, '')
});
But i am getting error like invalid ID
Kindly help
Currently, you are replacing the regex with empty space, so it will return the result 'abc123'. What you actually need is getting the string inside the brackets. You can use the below code to do it.
var EditedID = "abc[123]"
var regex = /\[([^\[\]]*)\]/
var result = ""
match = JSON.stringify(EditedID).match(regex)
if (match != null) {
result = match[1]
}
"result = match[1]" means that it will assign the value inside the brackets to result. If you want the value with both brackets, use match[0].
I assume that your EditedID is an object and somehow it will need the method "JSON.stringify" to make it become String. If your EditedID is already a String, just replace the match value to make it simpler
match = EditedID.match(regex)
If there is not match, the code won't run into the if condition so the value of result will just be an empty String.

Escape metacharacters and using it as string variable for selector

eg.
I have var myid="abc xyz"
then I escape metachars using function and get var x = "#"+escapechars(myid);
which evaluate to #abc\\xyz
Now when I try to do $(x) it doesn't get any element
but when I type $("#abc\\xyz") in watch it gets the element.
I am attaching a screenshot for same scenario.
Problem is : I want to select the element using variable
Thank you.
Here is the jsfiddle for my scenario.
http://jsfiddle.net/9hq4nzvx/3/
This >http://jsfiddle.net/9hq4nzvx/5/ solves the issue.
When we are using string variable that time we only need a single backslash instead of 2.
function escapechars now returns : "#abc\ xyz" which gets the element as needed.
var selection ="abc xyz";//this can be anything else comes from an array.
var x = "#"+escapeStr(selection); //"#abc\\\\\ xyz";
$(x).html("<h1>Hii</h1>");//why don't I get element here?
console.log(x);
alert(x);
$("#abc\\ xyz").append("<h2>bye</h2>");
function escapeStr(str) {//escape special chars from selectors
if (str)
return str.replace(/([ !"#$%&'()*+,.\/:;<=>?#[\\\]^`{|}~])/g, '\\$1');
return str;
}

TypeError : undefined is not a function when calling replace method

I know the code is very little and I'm missing something small.
fiddle : http://jsfiddle.net/0oa9006e/1/
code :
var veri = "+???+Girdiğiniz eposta adresi 'adfadf' geçersiz.-???-";
var a = veri.match(/\+[\?]*\+(.*)*\-[\?]*\-/g);
a = a.replace(/[\+\-\?]*/g , "");
alert(a);
String.match(param) method returns an Array containing all matches. and array in javascript doesn't have .replace method. hence Error. You could try out something like:
a = a.toString().replace(/[\+\-\?]*/g,""); // Array to string converstion
Your match is returning an array, which doesn't have replace. Try:
a = a[0].replace(/[\+\-\?]*/g , "");
var veri = "+???+Girdiğiniz eposta adresi 'adfadf' geçersiz.-???-";
var a = veri.match(/\+[\?]*\+(.*)*\-[\?]*\-/g);
// The variable 'a' is now an array.
// The first step in debugging is to always make sure you have the values
// you think you have.
console.log(a);
// Arrays have no replace method.
// Perhaps you are trying to access a[0]?
// or did you mean to modify `veri`?
a = a.replace(/[\+\-\?]*/g , "");
alert(a);
When veri.match(/\+[\?]*\+(.*)*\-[\?]*\-/g) is executed, your variable a is initialized to a JavaScript Array, which does not have a replace method.
Use a RegEx tool like Regex101 to see how your regular expression matches on the string veri, and then perform the replace operation on the appropriate element of that array.
Here's an example of your regular expression in use: http://regex101.com/r/hG3uI1/1
As you can see, your regular expression matches the entire string held by veri, so you want to perform the replace operation on the first (and only) element returned by match:
a = a[0].replace(/[\+\-\?]*/g , "");

Javascript perform arithmetic on captured regexp

I want to replace my title from its default to "*number* new messages | default"
Here is the code I have, it changes from default to 1 new messages fine, but it never goes above 1.
title = $('title').text();
regexp = /^(\d+)/
if (title.match(regexp))
$('title').text().replace(regexp, (parseInt("$1")+1).toString())
else
$('title').text('1 New Messages | Default')
You should be using a function as the second argument to replace, you also need to set the new value:
var title = $('title').text();
$('title').text(title.replace(regexp, function(m) { return parseInt(m, 10) + 1) }));
And, as usual, don't forget the radix argument when you call parseInt or you will be unpleasantly surprised sooner or later.
I came across this recently and the issue is to do with calling a function within the second argument of the replace function. The $1 is only valid if called directly in a string literal, not as a string argument to a function.
Another issue is that $('title').text().replace(regexp, (parseInt("$1")+1).toString()) will return a string. You need to pass the value you want to assign the text to as a function argument of the text() function like you have done in your else block.
Try this:
title = $('title').text();
regexp = /^(\d+)/
if (numToReplace = title.match(regexp))
$(title).text(title.replace(regexp, (parseInt(numToReplace[1])+1).toString()))
else
$('title').text('1 New Messages | Default')
And a JSFiddle: http://jsfiddle.net/KFW4G/
replace returns a new string, so you have to use text again to set the text to the result.

Categories

Resources