Assume i have a string
var str = " 1, 'hello' "
I'm trying to give a function the above values found in str but as integer and string- not as one string-
for example myFunc(1,'hello')
how can i achieve that
i tried using eval(str),
but I'm getting invalid token ,
How can i solve this?
The following should work with any number of arguments.
function foo(num, str) {
console.log(num, str);
}
const input = "1, 'hel,lo'";
const args = JSON.parse('[' + input.replace(/'/g, '"') + ']');
foo(...args);
You've almost got the right idea with eval(str) however, that isn't the thing you actually want to evaluate. If you do use eval(str), it is the same as saying eval(" 1, 'hello' ")
However, what you really want to do is:
eval("func(1, 'hello world')).
To do this you can do:
eval(func.name + '(' + str.trim() + ')');
Here we have:
func.name: The name of the function to call. You can of course hard code this. (ie just write "func(" + ...)
str.trim(): The arguments you want to pass into the given function. Here I also used .trim() to remove any additional whitespace around the string.
Take a look at the snippet below. Here I have basically written out the above line of code, however, I have used some intermediate variables to help spell out how exactly this works:
function func(myNum, myStr) {
console.log(myNum*2, myStr);
}
let str = " 1, 'hello, world'";
// Build the components for the eval:
let fncName = func.name;
let args = str.trim();
let fncStr = fncName + '(' + args + ')';
eval(fncStr);
Alternatively, if you only wish to pass in two arguments you can use .split(',') on your string to split the string based on the comma character ,.
Using split on " 1, 'hello' " will give you an array such as this one a:
let a = [" 1", "'hello'"];
Then cast your string to an integer and remove the additional quotes around your string by using .replace(/'/g, ''); (replace all ' quotes with nothing ''):
let numb = +a[0].trim(); // Get the number (convert it to integer using +)
let str = a[1].trim().replace(/'/g, ''); // get the string remove whitespace and ' around it using trim() and replace()
Now you can call your function using these two variables:
func(numb, str);
function func(myNum, myStr) {
console.log('The number times 2 is:', myNum*2, "My string is:", myStr);
}
let arguments = " 1, 'hello' ";
let arr = arguments.split(',');
let numb = +arr[0].trim(); // Argument 1
let str = arr[1].trim().replace(/'/g, ''); // Argument 2
func(numb, str);
I'm looking for a function that removes all occurrences of a substring in a string except the first one, so for example
function keepFirst(str, substr) { ... }
keepFirst("This $ is some text $.", "$");
should return: This $ is some text .
I could do it using split() and then for(){}, but is there a nicer solution?
This could be the shortest code that is somewhat efficient. It uses destructuring assignment.
function keepFirst(str, substr) {
const [
first,
...rest
] = str.split(substr);
return first + (rest.length
? substr + rest.join("")
: "");
}
This solution finds the index of the first occurence of rep and removes all of the reps after it.
console.log(keepFirst("This $ is some text $$ with $ signs.", "$"));
function keepFirst(str, rep) {
var fInd = str.indexOf(rep);
var first = str.substring(0, fInd + rep.length);
var rest = str.substring(fInd + rep.length);
return first + rest.replace(
new RegExp(rep.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), 'g'),
'');
}
I would like to remove the characters destructively from two points in a string, so when the string is called after the removal it would not include the removed characters.
Example
var string = "I am a string";
I'd like to: remove (0, 7);
When I call string again it should return:
console.log(string) => string
Example-2
var string = "I am a string";
I'd like to: remove (7, 10);
When I call string again it should return:
console.log(string) => I am a ing
See javascript substring.
For your example use this:
var string = "I am a string";
console.log(string.substring(7));
OUTPUTS
string
UPDATE
For removing a portionof a string, you can do it by concating the first wanted characters with the last wanted characters, something like this:
var string = "I am a string";
console.log(string.substr(0, 5) + string.substr(7));
OUTPUTS
I am string
If you want to have a direct function for removing portions of strings, see Ken White's answer that uses substr instead of substring. The difference between substr and substring is in the second parameter, for substring is the index to stop and for substr the length to return. You can use something like this:
String.prototype.replaceAt = function(index, charcount) {
return this.substr(0, index) + this.substr(index + charcount);
}
string.replaceAt(5, 2); // Outputs: "I am string"
Or if you want to use start and end like (7, 10), then have a function like this:
String.prototype.removeAt = function(start, end) {
return this.substr(0, start) + this.substr(end);
}
string.removeAt(7, 10); // Outputs: "I am a ing"
The easiest way is to just slice the front part and the back part and splice them back together:
var string = "I am a string";
string = string.substring(0, 7) + string.substring(10);
console.log(string);
// => I am a ing
I am so close to getting this, but it just isn't right.
All I would like to do is remove the character r from a string.
The problem is, there is more than one instance of r in the string.
However, it is always the character at index 4 (so the 5th character).
Example string: crt/r2002_2
What I want: crt/2002_2
This replace function removes both r
mystring.replace(/r/g, '')
Produces: ct/2002_2
I tried this function:
String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + char.length);
}
mystring.replaceAt(4, '')
It only works if I replace it with another character. It will not simply remove it.
Any thoughts?
var mystring = "crt/r2002_2";
mystring = mystring.replace('/r','/');
will replace /r with / using String.prototype.replace.
Alternatively you could use regex with a global flag (as suggested by Erik Reppen & Sagar Gala, below) to replace all occurrences with
mystring = mystring.replace(/\/r/g, '/');
EDIT:
Since everyone's having so much fun here and user1293504 doesn't seem to be coming back any time soon to answer clarifying questions, here's a method to remove the Nth character from a string:
String.prototype.removeCharAt = function (i) {
var tmp = this.split(''); // convert to an array
tmp.splice(i - 1 , 1); // remove 1 element from the array (adjusting for non-zero-indexed counts)
return tmp.join(''); // reconstruct the string
}
console.log("crt/r2002_2".removeCharAt(4));
Since user1293504 used the normal count instead of a zero-indexed count, we've got to remove 1 from the index, if you wish to use this to replicate how charAt works do not subtract 1 from the index on the 3rd line and use tmp.splice(i, 1) instead.
A simple functional javascript way would be
mystring = mystring.split('/r').join('/')
simple, fast, it replace globally and no need for functions or prototypes
There's always the string functions, if you know you're always going to remove the fourth character:
str.slice(0, 4) + str.slice(5, str.length)
Your first func is almost right. Just remove the 'g' flag which stands for 'global' (edit) and give it some context to spot the second 'r'.
Edit: didn't see it was the second 'r' before so added the '/'. Needs \/ to escape the '/' when using a regEx arg. Thanks for the upvotes but I was wrong so I'll fix and add more detail for people interested in understanding the basics of regEx better but this would work:
mystring.replace(/\/r/, '/')
Now for the excessive explanation:
When reading/writing a regEx pattern think in terms of: <a character or set of charcters> followed by <a character or set of charcters> followed by <...
In regEx <a character or set of charcters> could be one at a time:
/each char in this pattern/
So read as e, followed by a, followed by c, etc...
Or a single <a character or set of charcters> could be characters described by a character class:
/[123!y]/
//any one of these
/[^123!y]/
//anything but one of the chars following '^' (very useful/performance enhancing btw)
Or expanded on to match a quantity of characters (but still best to think of as a single element in terms of the sequential pattern):
/a{2}/
//precisely two 'a' chars - matches identically as /aa/ would
/[aA]{1,3}/
//1-3 matches of 'a' or 'A'
/[a-zA-Z]+/
//one or more matches of any letter in the alphabet upper and lower
//'-' denotes a sequence in a character class
/[0-9]*/
//0 to any number of matches of any decimal character (/\d*/ would also work)
So smoosh a bunch together:
var rePattern = /[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/g
var joesStr = 'aaaAAAaaEat at Joes123454321 or maybe aAaAJoes all you can eat098765';
joesStr.match(rePattern);
//returns ["aaaAAAaaEat at Joes123454321", "aAaAJoes all you can eat0"]
//without the 'g' after the closing '/' it would just stop at the first match and return:
//["aaaAAAaaEat at Joes123454321"]
And of course I've over-elaborated but my point was simply that this:
/cat/
is a series of 3 pattern elements (a thing followed by a thing followed by a thing).
And so is this:
/[aA]{4,8}(Eat at Joes|Joes all you can eat)[0-5]+/
As wacky as regEx starts to look, it all breaks down to series of things (potentially multi-character things) following each other sequentially. Kind of a basic point but one that took me a while to get past so I've gone overboard explaining it here as I think it's one that would help the OP and others new to regEx understand what's going on. The key to reading/writing regEx is breaking it down into those pieces.
Just fix your replaceAt:
String.prototype.replaceAt = function(index, charcount) {
return this.substr(0, index) + this.substr(index + charcount);
}
mystring.replaceAt(4, 1);
I'd call it removeAt instead. :)
For global replacement of '/r', this code worked for me.
mystring = mystring.replace(/\/r/g,'');
This is improvement of simpleigh answer (omit length)
s.slice(0, 4) + s.slice(5)
let s = "crt/r2002_2";
let o = s.slice(0, 4) + s.slice(5);
let delAtIdx = (s, i) => s.slice(0, i) + s.slice(i + 1); // this function remove letter at index i
console.log(o);
console.log(delAtIdx(s, 4));
let str = '1234567';
let index = 3;
str = str.substring(0, index) + str.substring(index + 1);
console.log(str) // 123567 - number "4" under index "3" is removed
return this.substr(0, index) + char + this.substr(index + char.length);
char.length is zero. You need to add 1 in this case in order to skip character.
Maybe I'm a noob, but I came across these today and they all seem unnecessarily complicated.
Here's a simpler (to me) approach to removing whatever you want from a string.
function removeForbiddenCharacters(input) {
let forbiddenChars = ['/', '?', '&','=','.','"']
for (let char of forbiddenChars){
input = input.split(char).join('');
}
return input
}
Create function like below
String.prototype.replaceAt = function (index, char) {
if(char=='') {
return this.slice(0,index)+this.substr(index+1 + char.length);
} else {
return this.substr(0, index) + char + this.substr(index + char.length);
}
}
To replace give character like below
var a="12346";
a.replaceAt(4,'5');
and to remove character at definite index, give second parameter as empty string
a.replaceAt(4,'');
If it is always the 4th char in yourString you can try:
yourString.replace(/^(.{4})(r)/, function($1, $2) { return $2; });
It only works if I replace it with another character. It will not simply remove it.
This is because when char is equal to "", char.length is 0, so your substrings combine to form the original string. Going with your code attempt, the following will work:
String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + 1);
// this will 'replace' the character at index with char ^
}
DEMO
You can use this: if ( str[4] === 'r' ) str = str.slice(0, 4) + str.slice(5)
Explanation:
if ( str[4] === 'r' )
Check if the 5th character is a 'r'
str.slice(0, 4)
Slice the string to get everything before the 'r'
+ str.slice(5)
Add the rest of the string.
Minified: s=s[4]=='r'?s.slice(0,4)+s.slice(5):s [37 bytes!]
DEMO:
function remove5thR (s) {
s=s[4]=='r'?s.slice(0,4)+s.slice(5):s;
console.log(s); // log output
}
remove5thR('crt/r2002_2') // > 'crt/2002_2'
remove5thR('crt|r2002_2') // > 'crt|2002_2'
remove5thR('rrrrr') // > 'rrrr'
remove5thR('RRRRR') // > 'RRRRR' (no change)
If you just want to remove single character and
If you know index of a character you want to remove, you can use following function:
/**
* Remove single character at particular index from string
* #param {*} index index of character you want to remove
* #param {*} str string from which character should be removed
*/
function removeCharAtIndex(index, str) {
var maxIndex=index==0?0:index;
return str.substring(0, maxIndex) + str.substring(index, str.length)
}
I dislike using replace function to remove characters from string. This is not logical to do it like that. Usually I program in C# (Sharp), and whenever I want to remove characters from string, I use the Remove method of the String class, but no Replace method, even though it exists, because when I am about to remove, I remove, no replace. This is logical!
In Javascript, there is no remove function for string, but there is substr function. You can use the substr function once or twice to remove characters from string. You can make the following function to remove characters at start index to the end of string, just like the c# method first overload String.Remove(int startIndex):
function Remove(str, startIndex) {
return str.substr(0, startIndex);
}
and/or you also can make the following function to remove characters at start index and count, just like the c# method second overload String.Remove(int startIndex, int count):
function Remove(str, startIndex, count) {
return str.substr(0, startIndex) + str.substr(startIndex + count);
}
and then you can use these two functions or one of them for your needs!
Example:
alert(Remove("crt/r2002_2", 4, 1));
Output: crt/2002_2
Achieving goals by doing techniques with no logic might cause confusions in understanding of the code, and future mistakes, if you do this a lot in a large project!
The following function worked best for my case:
public static cut(value: string, cutStart: number, cutEnd: number): string {
return value.substring(0, cutStart) + value.substring(cutEnd + 1, value.length);
}
The shortest way would be to use splice
var inputString = "abc";
// convert to array and remove 1 element at position 4 and save directly to the array itself
let result = inputString.split("").splice(3, 1).join();
console.log(result);
This problem has many applications. Tweaking #simpleigh solution to make it more copy/paste friendly:
function removeAt( str1, idx) {
return str1.substr(0, idx) + str1.substr(idx+1)
}
console.log(removeAt('abbcdef', 1)) // prints: abcdef
Using [index] position for removing a specific char (s)
String.prototype.remplaceAt = function (index, distance) {
return this.slice(0, index) + this.slice(index + distance, this.length);
};
credit to https://stackoverflow.com/users/62576/ken-white
So basically, another way would be to:
Convert the string to an array using Array.from() method.
Loop through the array and delete all r letters except for the one with index 1.
Convert array back to a string.
let arr = Array.from("crt/r2002_2");
arr.forEach((letter, i) => { if(letter === 'r' && i !== 1) arr[i] = "" });
document.write(arr.join(""));
In C# (Sharp), you can make an empty character as '\0'.
Maybe you can do this:
String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + char.length);
}
mystring.replaceAt(4, '\0')
Search on google or surf on the interent and check if javascript allows you to make empty characters, like C# does. If yes, then learn how to do it, and maybe the replaceAt function will work at last, and you'll achieve what you want!
Finally that 'r' character will be removed!
I need to search a string for any numbers in it and increase the numbers by 1. So that this 'sermon[thesis][1][name][2]' becomes 'sermon[thesis][2][name][3]'.
This will do the trick:
"sermon[thesis][1][name][2]".replace(/\[(\d+)\]/g, function(match, number) {
return "[" + (Number(number) + 1) + "]";
});
Working demo: jsFiddle.
EDIT:
To increment the last number, you would add a dollar sign $ before the last /, here's a demo: jsFiddle.
You can use replace, it can actually take a function as the replacement "string".
var str = 'sermon[thesis][1][name][2]';
str = str.replace(/(\d+)/g, function(a){
return parseInt(a,10) + 1;
});
console.log(str); //'sermon[thesis][2][name][3]'
You can do something like this:
var str = "sermon[thesis][1][name][2]";
var newStr = str.replace(new RegExp("\\d+", "g"), function (n) {
return parseInt(a, 10) + 1;
});
Basicly, the function would be called with the text been captured by the expression \d+,the text return from the function would be use to replace the captured text.
You can use the replace() function to match any number with a regular expression and then return that value incremented by 1 to replace it:
var string = '[1][2]';
string.replace(/[0-9]+/g,function(e){return parseInt(e,10)+1})); //Returns [2][3]
Working Example