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.'));
Related
This question already has answers here:
How to remove text from a string?
(16 answers)
Closed 10 months ago.
Given a regex how can i split filter a string like this :
"https://theuselessweb.com/ hello https://theuselessweb.com/ hello"
To a string like this :
"hello hello"
Ive tried something like
string.match(regex).join(' ')
But this doesnt reeally work
Any solutions?
Here is one way by splitting the string into words and then filtering out the urls.
const str = "https://theuselessweb.com/ hello https://theuselessweb.com/ hello";
const res = str.split(" ").filter(w => !w.includes("https://")).join(" ");
console.log(res);
You can split the input by split(' ') and filter out the array using a regex expression you want.
const inputStr = "https://theuselessweb.com/ hello https://theuselessweb.com/ hello";
const inputArr = inputStr.split(' ');
const regex = new RegExp('https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,}');
const output = inputArr.filter(word => !regex.test(word));
console.log(output);
This question already has answers here:
How do I make the first letter of a string uppercase in JavaScript?
(96 answers)
Closed 1 year ago.
I tried the below code in JavaScript:
console.log(str.toLowerCase().trim().replace(str[0], str[0].toUpperCase()));
Case 1 - str = 'variable':
const str = 'variable';
console.log(str.toLowerCase().trim().replace(str[0], str[0].toUpperCase()));
It gives the expected output which is, 'Variable', i.e, the first letter of the string is in uppercase.
Case 2 - str = 'Variable':
const str = 'Variable';
console.log(str.toLowerCase().trim().replace(str[0], str[0].toUpperCase()));
It gives the a strange output- 'variable'.
I am quite new to JavaScript and am unable to understand what the reason is for this behavior.
const str = 'Variable';
console.log(str.toLowerCase().trim().replace(str[0], str[0].toUpperCase()));
str is a constant, and a string (strings are immutable); it is always
const str = 'Variable';
If you take str[0], you get V.
So, .toLowerCase().trim().replace(str[0] will never match if the first character is upper-case, because the upper-case str[0] will not be contained inside the trimmed, lower-cased string.
I'd save the lower-cased version of the string in a variable first, so you can access that string's [0].
const str = 'Variable';
const lower = str.toLowerCase().trim();
console.log(lower.replace(lower[0], lower[0].toUpperCase()));
Or, to be more precise, extract only the first character, upper-case it, and lower-case the rest.
const str = 'Variable';
const result = (
str[0].toUpperCase() +
str.slice(1).toLowerCase()
);
console.log(result);
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:
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)
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