This question already has answers here:
Is there a RegExp.escape function in JavaScript?
(18 answers)
Closed 3 years ago.
I need to split a string by multiple delimiters.
My string is var str = "2$4#3*5"
My array of delimiters (separators) is var del = ["$","#", "*"]
I'm using a regular expression but it is not working.
str.split(new RegExp(del.join('|'), 'gi'));
The results should be ["2","4","3","5"]
However I'm getting an error SyntaxError: Invalid regular expression: /*/: Nothing to repeat
When I remove the * the resulting array is ["2$3',"3", "5"]
How can I split with multiple delimiters from an array of delimiters?
and why does this not work with $ and *?
You need to escape the special characters first - replace function from this answer:
var str = "2$4#3*5";
var del = ["$", "#", "*"];
const res = str.split(new RegExp(del.map(e => e.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join("|"), "gi"));
console.log(res);
Try like this.
I passed in the Regex expression in split.
var str = "2$4#3*5"
var res= str.split(/[$,#,*]+/)
console.log(res)
Related
This question already has answers here:
Replace all occurrences of character except in the beginning of string (Regex)
(3 answers)
Remove all occurrences of a character except the first one in string with javascript
(1 answer)
Closed 1 year ago.
I’m looking to remove + from a string except at the initial position using javascript replace and regex.
Input: +123+45+
Expected result: +12345
Please help
const string = '+123+45+'
console.log(string.replace(/([^^])\+/g, '$1'))
https://regexr.com/61g3c
You can try the below regex java script. Replace all plus sign except first occurrence.
const givenString = '+123+45+'
let index = 0
let result = givenString.replace(/\+/g, (item) => (!index++ ? item : ""));
console.log(result)
input = '+123+45+';
regex = new RegExp('(?!^)(\\+)', 'g');
output = input.replace(regex, '');
console.log(output);
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)
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.'));
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
This question already has answers here:
JS regex to split by line
(7 answers)
Closed 6 years ago.
I have res from JSON with that string :
"nID_ServiceData
0-151975019"
this string with <br>, or return character...
when i try to split this:
var x= "nID_ServiceData
0-151975019";
var y = x.split(' ');
it became ["nID_ServiceData↵0-151975019"], so I try again :
y.split('↵');
but again I have - ["nID_ServiceData↵0-151975019"].
Where I make mistake?
The return character is represented as \n in javascript, so x.split("\n"); should work.
var y = x.split(' '); is trying to split on a space, but your string has a newline (\n). Split on a newline, instead of a space.
var x = "nID_ServiceData\n0-151975019";
var y = x.split("\n");
If the newline might be a CRLF combination (\r\n) but may not (just \n), you can use a regular expression to do the split:
var x = "nID_ServiceData\n0-151975019";
var y = x.split(/\r?\n/);