Javascript Array - Split string at numbers [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have an unknown string containing a set of numbers like so:
var string = "stuff 1.23! (456) 789 stuff";
I would like to split the array, in order to modify the numbers and later rejoin the array. The result I'm looking for should look like this:
var result = ['stuff ', 1.23, '! (', 456, ') ', 789, ' stuff'];
Is there a better solution than to loop through each character individually? Thanks!

use a character class to split the values:
/(-?[\d.]+)/
-? May start with a negative such as -123
[\d.]+ Has one or more numbers and decimals
var string = "stuff 1.23! (456) 789 stuff -234".split(/(-?[\d.]+)/);
console.log(string)

The ideal solution really depends on what exactly you are doing with the data. One simple solution is a regular expression with replace.
var string = "stuff 1.23! (456) 789 stuff";
var updated = string.replace(/\d+(\.\d+)?/g, function (m) {
console.log(m);
return "xxx";
})
console.log(updated)

A regular expression is an expression you can use to search within your string, in you case, for digits. Create a regular expression which searches for sequences of digits, and you'll be able to use the split method on your string to create an array of strings like you specified.

Related

How to match numbers followed by any combination of special characters and spaces using regex [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I am a newbie with regex and I am having trouble trying to match some parts of a string so I can remove it from a piece of entered text. I want to match digits followed by a sequence of a combination of any special characters + spaces. There could also be non Latin characters that should not be removed inside the sequence (for example Ñ).
for example inputted it may look like:
11#- &-.text
11 $ab*cÑ .somewords123
outputted I would expect
text
abcÑsomewrods123
I am using javascript replaceall method with regex to find it. So far I have something basic like this regex
.replaceAll(/\d+(\#|\s)+(\-|\$)+(\s|\&)+(\&)+(\-)+(\.)/g, '');
Is there a way to write this more efficiently so that it captures any special characters since the text can contain more different special chars than in the examples? Or is this a situation better handled with pure JS?
Thanks in advance for your help.
You should ether have blacklist of what you calling special characters, or whitelist of the allowed characters.
for blacklist it gonna look like:
const blacklist = "!##$%^&*()_+.";
const exampleInputs = [
"te&*st+_1.",
"te%%st^*2",
"t###es*(*(*t3"
];
function removeSpecialChars(str) {
const reg = new RegExp(`[${blacklist}]`, "g");
return str.replace(reg, "");
}
exampleInputs.forEach(input => console.log(removeSpecialChars(input)));
for whitelist it gonna looks like:
const whitelist = "0-9a-zA-Z";
const exampleInputs = [
"te&*st+_1.",
"te%%st^*2",
"t###es*(*(*t3"
];
function removeSpecialChars(str) {
const reg = new RegExp(`[^${whitelist}]`, "g");
return str.replace(reg, "");
}
exampleInputs.forEach(input => console.log(removeSpecialChars(input)));

Split operating without concating [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have a string 'OR-xxxxxxxx-001-01'.
I need to split it as 'OR-xxxxxxx-001' and '01'. Is it possible without split by '-' and concatenating again ??
In Java, use lastIndexOf:
String string = "OR-xxxxxxxx-001-01";
int lastDash = string.lastIndexOf('-');
String prefix = string.substring(0, lastDash); // OR-xxxxxxx-001
String suffix = string.substring(lastDash + 1); // 01
This solution is for JavaScript (Java and JavaScript is not the same thing).
Since you don't want to split by - it's possible to do it with indexes. You haven't specified if it's of fixed length or not (which this solution depends on), but this should do the trick:
t = 'OR-xxxxxxxx-001-01'
str = t.slice(0, 12) + t.slice(16);
Will give str = 'OR-xxxxxxxx-01'
You could use a split with a positive look-ahead:
String str = "OR-xxxxxxxx-001-01";
String[] split = str.split("-(?=[^-]+$)");
[^-]: any character other than -.
+: repeated one or more times
$: at the end of the String
Then the (?= ... ) is used for the positive look-ahead, so it won't be removed by the split. This means only the - outside the parenthesis act as delimiter to split on.
Try it online.
PS: In Java.

Strip specific characters and replaced with word [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
If I have this string:
This string should #[1234] by another word
I want to replace to remove # [ ] and replace 1234 with 'test' word for example so the result is:
This string should test by another word
Is there any way to do this with js?
You can use regular expression to repalce your #[XXX] by test with the following code :
var string = "This string should #[1234] by another word";
console.log(string.replace(/#\[[0-9]+\]/gi, "test"));
I suggest to define a mapping from ids to replacements first.
Then you use string.replace(regex, callback) with a regex that matches #[1234] or any other id within the brackets and captures the id within a capture group.
Finally, you provide a callback which receives the value of the capture group as the second parameter and performs the replacement according to your mapping:
const input = 'This string should #[1234] by another word';
const replacements = {'1234': 'test'};
const output = input.replace(/#\[(\d+)\]/g, (match, id) => replacements[id]);
console.log(output);
I'm guessing you have multiple texts to replace? If so, you can use the String.replace function with a callback, which provides the replacement value. Something like this:
var repls = {
"1234": "test"
};
var text = "This string should #[1234] by another word";
var result = text.replace(/#\[([0-9]+)\]/g, function(entireMatch, key) {
return repls[key];
});
console.log(result);
Here's some code that doesn't use regular expressions, just split() and join(), and with strings as delimiters.
str='This string should #[1234] by another word';
console.log(str.split('#[1234]').join('test'));

split a string with comma and colon [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a string like as shown below:
var String = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string,with comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string , with comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:String,with comma"
Where xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx represents an alphanumeric generated Id and after the colon is a string related to that Id.The string can be a string with comma or without comma.What I wanted was that I wanted to split the string such that I get an array with ID:its corresponding string , just like shown below.
["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string,with comma","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma",
"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string , with comma","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:String,with comma"]
HOW I ACCOMPLISHED THIS
I used the javascript split function where i split the string by comma followed by 36 characters (for ID) and colon.
String.split(/,(?=.{36}:)/);
PS: I apologize as previously I was not able to ask the question in the correct manner.Hope this time people understand it.
You could use String#split by comma and a look ahead for numbers and colon.
var x = "123456:a,b,c,435213:r,567876:e,363464:t,y,u";
array = x.split(/,(?=\d+:)/);
console.log(array);
For alphanumeric values
var x = "1A3456:a,b,c,43Y213:r,567W76:e,363x64:t,y,u";
array = x.split(/,(?=[a-z0-9]+:)/i);
console.log(array);
You can use the method .split(). I used the "$" as a split sign instead of "," because i thought you would like to keep them.
var values = "123456:a,b,c$435213:r$567876:e$363464:t,y,u".split("$");
var x = values[0];
console.log(values)

Get regex rules for a capture group [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am looking for a method to get the regex rules, for a capture group.
So if I had: /(\w) (\d)/ I would want $1 = /\w/ and $2 = /\d/.
Is there a method for this?
Provided that the regex is valid and no nested groups are used, then you can try this out.
var arr = (regex + "").match(/\(.*?\)/g).map(function(rule){
return rule.replace(/[()]/g, "");
});
Now, arr[0] will have rule of group1, arr[1] will be group2 and so on.
Although I don't know of any direct way to do this on a regex rule given by /(rule1)(rule2)/ you could build the regex rule using strings and specify your grouping in different strings.
var group1 = '([A-Za-z]+)',
group2 = '(\\d+)',
r = new RegExp(group1+group2);
r.test('hello1234');
To get the groups from a regex string you could run a regex on that regex string to extract the groups. If your regex string is "(\w+)(\d+)" then you'd have a regex to extract the groups as /(\([^\)\))+/

Categories

Resources