Get everything in string after a single comma [duplicate] - javascript

This question already has answers here:
How do I split a string with multiple separators in JavaScript?
(25 answers)
How can I convert a comma-separated string to an array?
(19 answers)
Closed 4 years ago.
I have some problem with my string, the variable name is accountcode. I want only part of the string. I want everything in the string which is after the first ,, excluding any extra space after the comma. For example:
accountcode = "xxxx, tes";
accountcode = "xxxx, hello";
Then I want to output like tes and hello.
I tried:
var s = 'xxxx, hello';
s = s.substring(0, s.indexOf(','));
document.write(s);

Just use split with trim.
var accountcode = "xxxx, tes";
var result= accountcode.split(',')[1].trim();
console.log(result);

You can use String.prototype.split():
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
You can use length property of the generated array as the last index to access the string item. Finally trim() the string:
var s = 'xxxx, hello';
s = s.split(',');
s = s[s.length - 1].trim();
document.write(s);

You can use string.lastIndexOf() to pull the last word out without making a new array:
let accountcode = "xxxx, hello";
let lastCommaIndex = accountcode.lastIndexOf(',')
let word = accountcode.slice(lastCommaIndex+1).trim()
console.log(word)

You can split the String on the comma.
var s = 'xxxx, hello';
var parts = s.split(',');
console.log(parts[1]);
If you don't want any leading or trailing spaces, use trim.
var s = 'xxxx, hello';
var parts = s.split(',');
console.log(parts[1].trim());

accountcode = "xxxx, hello";
let macthed=accountcode.match(/\w+$/)
if(matched){
document.write(matched[0])
}
here \w+ means any one or more charecter
and $ meand end of string
so \w+$ means get all the character upto end of the sting
so here ' ' space is not a whole character so it started after space upto $
the if statement is required because if no match found than macthed will be null , and it found it will be an array and first element will be your match

Related

Remove string quotes from a array javascript? [duplicate]

This question already has answers here:
Parsing string as JSON with single quotes?
(10 answers)
Convert string into an array of arrays in javascript
(3 answers)
Closed 2 years ago.
I'm trying to remove " " from an array inside a string.
var test = "['a']"
var test1 = "['a','b']"
Expected Output:
var test_arr = ['a']
var test1_arr = ['a','b']
I tried replacing, didn't work
var test_arr = test.replace(/\"/, '');
I see two ways to accomplish that.
JSON.parse('["a","b"]') note that the values need to be in double-quotes.
"['a','b']".replace(/[['\]]/g, '').split(',') note that you need to split after replacing the unwanted chars
Both yield an array containing the original strings.
You can simply convert the single quotes inside the strings to double quotes first to convert the string to a valid JSON, and then we can use JSON.parse to get the required array like:
var test = "['a']"
var test1 = "['a','b']"
var parseStr = str => JSON.parse(str.replace(/'/g, '"'))
var test_arr = parseStr(test)
var test1_arr = parseStr(test1)
console.log(test_arr)
console.log(test1_arr)

Non destructive split() in JavaScript? [duplicate]

This question already has answers here:
Split string into array without deleting delimiter?
(5 answers)
Closed 3 years ago.
You can make an array from a string and remove a certain character with split:
const str = "hello world"
const one = str.split(" ")
console.log(one) // ["hello", "world"]
But how can you split a string into an array without removing the character?
const str = "Hello."
["Hello", "."] // I need this output
While you can use a capture group while splitting to keep the result in the final output:
const str = "Hello.";
console.log(
str.split(/(\.)/)
);
This results in an extra empty array item. You should probably use .match instead: either match .s, or match non-. characters:
const match = str => str.match(/\.|[^.]+/g);
console.log(match('Hello.'));
console.log(match('Hello.World'));
console.log(match('Hello.World.'));

jQuery multiple replace [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 8 years ago.
I'm trying to remove the euro sign from my string.
Since the string looks like this €33.0000 - €37.5000, I first explode to string on the - after I try to remove the euro sign.
var string = jQuery('#amount').val();
var arr = string.split(' - ');
if(arr[0] == arr[1]){
jQuery(this).find('.last').css("display", "none");
}else{
for(var i=0; i< arr.length; i++){
arr[i].replace('€','');
console.log(arr[i]);
}
}
When I try it on my site, the euro signs aren't removed, when I get the string like this
var string = jQuery('#amount').val().replace("€", "");
Only the first euro sign is removed
.replace() replace only the fisrt occurence with a string, and replace all occurences with a RegExp:
jQuery('#amount').val().replace(/€/g, "")
Try using a regular expression with global replace flag:
"€33.0000 - €37.5000".replace(/€/g,"")
First get rid of the € (Globally), than split the string into Array parts
var noeur = str.replace(/€/g, '');
var parts = noeur.split(" - ");
The problem with your first attempt is that the replace() method returns a new string. It does not alter the one it executes on.
So it should be arr[i] = arr[i].replace('€','');
Also the replace method, by default, replaces the 1st occurrence only.
You can use the regular expression support and pass the global modifier g so that it applies to the whole string
var string = Query('#amount').val().replace(/€/g, "");
var parts = /^€([0-9.]+) - €([0-9.]+)$/.exec(jQuery('#amount').val()), val1, val2;
if (parts) {
val1 = parts[1];
val2 = parts[2];
} else {
// there is an error in your string
}
You can also tolerate spaces here and there: /^\s*€\s*([0-9.]+)\s*-\s*€\s*([0-9.]+)\s*$/

How to split the values in JavaScript

I have to split the values using JavaScript and want to find the last occuring slash / from a string and replace the contents after the last slash / For example:
var word = "www.abc/def/ghf/ijk/**default.aspx**";
should become
var word ="www.abc/def/ghf/ijk/**replacement**";
The number of slashes may vary each time.
Try using regexp:
"www.abc/def/ghf/ijk/default.aspx".replace(/\/[^\/]+$/, "/replacement");
An alternative without regular expression (I just remembered lastIndexOf() method)
var word = "www.abc/def/ghf/ijk/default.aspx";
word = word.substring(0, word.lastIndexOf("/")) + "/replacement";
You can array split on '/', then pop the last element off the array, and rejoin.
word = word.split('/');
word.pop();
word = word.join('/') + replacement;
How about the KISS principle?
var word = "www.abc/def/ghf/ijk/default.aspx";
word = word.substring(0, word.lastIndexOf("/")) + "/replacement";
What about using a combination of the join() and split() functions?
var word = "www.abc/def/ghf/ijk/default.aspx";
// split the word using a `/` as a delimiter
wordParts = word.split('/');
// replace the last element of the array
wordParts[wordParts.length-1] = 'replacement';
// join the array back to a string.
var finalWord = wordParts.join('/');
The number of slashes doesn't matter here because all that is done is to split the string at every instance of the delimiter (in this case a slash).
Here is a working demo
Use regexp or arrays, something like:
[].splice.call(word = word.split('/'), -1, 1, 'replacement');
word = word.join('/');

split string based on a symbol

I'm trying to split a string into an array based on the second occurrence of the symbol _
var string = "this_is_my_string";
I want to split the string after the second underscore. The string is not always the same but it always has 2 or more underscores in it. I always need it split on the second underscore.
In the example string above I would need it to be split like this.
var split = [this_is, _my_string];
var string = "this_is_my_string";
var firstUnderscore = string.indexOf('_');
var secondUnderscore = string.indexOf('_', firstUnderscore + 1);
var split = [string.substring(0, secondUnderscore),
string.substring(secondUnderscore)];
Paste it into your browser's console to try it out. No need for a jsFiddle.
var string = "this_is_my_string";
var splitChar = string.indexOf('_', string.indexOf('_') + 1);
var result = [string.substring(0, splitChar),
string.substring(splitChar, string.length)];
This should work.
var str = "this_is_my_string";
var matches = str.match(/(.*?_.*?)(_.*)/); // MAGIC HAPPENS HERE
var firstPart = matches[1]; // this_is
var secondPart = matches[2]; // _my_string
This uses regular expressions to find the first two underscores, and captures the part up to it and the part after it. The first subexpression, (.*?_.*?), says "any number of characters, an underscore, and again any number of characters, keeping the number of characters matched as small as possible, and capture it". The second one, (_.*) means "match an underscore, then any number of characters, as much of them as possible, and capture it". The result of the match function is an array starting with the full matched region, followed by the two captured groups.
I know this post is quite old... but couldn't help but notice that no one provided a working solution. Here's one that works:
String str = "this_is_my_string";
String undScore1 = str.split("_")[0];
String undScore2 = str.split("_")[1];
String bothUndScores = undScore1 + "_" + undScore2 + "_";
String allElse = str.split(bothUndScores)[1];
System.out.println(allElse);
This is assuming you know there will always be at least 2 underscores - "allElse" returns everything after the second occurrence.

Categories