ToString() and .replace in one line? - javascript

Is it possible to combine these two lines of code into one?
Meaning, can we do a ToString() and .replace() in one line?
var mySecondVar = myFirstVar.ToString()
mySecondVar = mySecondVar.replace("a","u");

Yes, you can chain the methods.
myFirstVar.toString().replace('a', 'u')
Note:
ToString should be toString
String#replace will only replace the first occurrence of the string. To replace all occurrences use replace with RegEx

You can use:
var mySecondVar = myFirstVar.toString().replace("a","u");

Related

How to parse functions names from string using javascript?

I'm looking for a reliable way to get function names from a string. The string values can be something like this:
let str = 'qwe(); asd();zxc()'
//or
let str = 'qwe("foo");asd(1);zxc();'
//etc.
I want to have an array
['qwe', 'asd', 'zxc']
I tried str.split(';') but how do I get rid of parenthesis and anything they can hold? Is there a regexp that will match all symbols on the left of some other symbol?
You can use this simple regex to find function names in .match()
var str = "qwe(); asd();zxc()";
console.log(str.match(/\w+(?=\()/g));
The first case it's fairly simple with regex a simple
[A-Za-z]\w+
would suffice.
on the second case it's a little bit trickier but maybe supressing the match for this
"(.*?)"
maybe a possibility

remove all characters of a string after 5th character?

I need to remove all characters of a string after 5th character,
for example
my string is
P-CI-7-C-71
and the output should be like
P-CI-
Use substring
alert("P-CI-7-C-71".substring(0, 5));
So you can use it like
var str='P-CI-7-C-71'.substring(0, 5);
You can also use substr, that will work the same in this case but remember they work differently so they are not generally interchangeable
var str='P-CI-7-C-71'.substr(0, 5);
Difference can be noticed in the prototype
str.substring(indexStart[, indexEnd])
VS
str.substr(start[, length])
Extracting String Parts
There are 3 methods for extracting a part of a string:
slice(start, end)
substring(start, end)
substr(start, length)
With String#substring:
The substring() method returns a subset of a string between one index and another, or through the end of the string.
document.write('P-CI-7-C-71'.substring(0, 5));
Try this:
alert('P-CI-7-C-71'.substring(0,5));
var str = 'P-CI-7-C-71';
var res = str.slice(0,5);
alert(res);
Use Can use substring function in the JS
the Substring(StringName,StartPosition, End Position);

using regular expression to get strings among commas

I am doing some JavaScript coding and have to process a string to a array.
The original string is this: "red,yellow,blue,green,grey"
What I want to get is an array like this: ["red","yellow","blue","green","grey"]
I have tried to write a function to do this, use indexOf() to get the position of commas then do some further processing. But I think it's to heavy this way. Is there a better way to use regular expression or some existed JavaScript method to implement my purpose?
Thanks all.
use string.split function to split the original string by comma.......
string.split(",")
You can use split:
The split() method splits a String object into an array of strings by separating the string into substrings.
var arr = "red,yellow,blue,green,grey".split(',');
OR
You can also use regex:
var arr = "red,yellow,blue,green,grey".match(/\w+/g);
Try the string.split() method. For further details refer to:
http://www.w3schools.com/jsref/jsref_split.asp
var str = "red,yellow,blue,green,grey";
var res = str.split(",");
you can use .split() function.
Example
.split() : Split a string into an array of substrings:
var str = "red,yellow,blue,green,grey";
var res = str.split(",");
alert(res);
You can use following regular expression ..
[^,]*

Splitting and returning part of a string

I have two strings such as:
sometext~somemoretext~extratext
and
sometext~otherextratext
I wish to crop off the last tilde (~) and all text to the right. For instance, the above two strings would result in:
sometext~somemoretext
and
sometext
Thanks
lastIndexOf(char) returns the position of the last found occurrence of a specified value in a string
substring(from, to) extracts the characters from a string, between two specified indices, and returns the new sub string
For instance:
var txt = 'sometext~somemoretext~extratext';
txt = txt.substring(0, txt.lastIndexOf('~'));
DEMO
I strongly suggest you to read the doc on the Javascript String Object
return theString.replace(/~[^~]*$/, '');
You can do this using a regular expression with the .replace() DOCs method.
var str = 'sometext~somemoretext~extratext';
str = str.replace(/~[\w\s]+$/, '');
Here is a jsFiddle of the above code for you to run: http://jsfiddle.net/NELFB/
you can use substr to split the string, then rebuild them for what ever you need
var someString = "sometext~otherextratext";
someString = someString.split('~');
this will give you an array, which you can use like someString[0];
use .replace('~', '') if you need to further remove the ones at the end of strings
this should do it
function removeExtra(input){
return input.substr(0,input.lastIndexOf('~'))
}

Is it possible to compare a char to regexp?

I want to check if a single character matches a set of possible other characters so I'm trying to do something like this:
str.charAt(0) == /[\[\]\.,-\/#!$%\^&\*;:{}=\-_`~()]/
since it doesn't work is there a right way to do it?
Use test
/[\[\]\.,-\/#!$%\^&\*;:{}=\-_`~()]/.test(str.charAt(0))
Yes, use:
if(str.charAt(0).match(/[\[\]\.,-\/#!$%\^&\*;:{}=\-_`~()]/))
charAt just returns a one character long string, there is no char type in Javascript, so you can use the regular string functions on it to match against a regex.
Another option, which is viable as long as you are not using ranges:
var chars = "[].,-/#!$%^&*;:{}=-_`~()";
var str = '.abc';
var c = str.charAt(0);
var found = chars.indexOf(c) > 1;
Example: http://jsbin.com/esavam
Another option is keeping the characters in an array (for example, using chars.split('')), and checking if the character is there:
How do I check if an array includes an object in JavaScript?

Categories