0

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);
Makyen
  • 31,849
  • 12
  • 86
  • 121
senaa
  • 63
  • 3
  • 8

5 Answers5

3

Just use split with trim.

var accountcode = "xxxx, tes";
var result= accountcode.split(',')[1].trim();
console.log(result);
Abana Clara
  • 4,602
  • 3
  • 18
  • 31
4b0
  • 21,981
  • 30
  • 95
  • 142
3

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)
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Mark
  • 90,562
  • 7
  • 108
  • 148
3

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);
Mamun
  • 66,969
  • 9
  • 47
  • 59
2

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());
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1
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

Pranoy Sarkar
  • 1,965
  • 14
  • 31