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 8 years ago.
Improve this question
How are you guys doing?
I'd like to ask today if you could help me with a tricky question that I was unable to solve on my own.
I [have] strings that [are] like this.
I was looking for a way to get "have" and "are" and form an array with them using JavaScript. Please notice that this is an example. Sometimes I have several substrings between braces, sometimes I don't have braces at all on my strings.
My attempts focused mostly on using .split method and regex to accomplish it, but the closest I got to success was being able to extract the first value only.
Would any of you be so kind and lend me an aid on that?
I tried using the following.
.split(/[[]]/);
You can use the exec() method in a loop, pushing the match result of the captured group to the results array. If the string has no square brackets, you will get an empty matches array [] returned.
var str = 'I [have] strings that [are] like this.'
var re = /\[([^\]]*)]/g,
matches = [];
while (m = re.exec(str)) {
matches.push(m[1]);
}
console.log(matches) //=> [ 'have', 'are' ]
Note: This will only work correctly if the brackets are balanced, will not perform on nested brackets.
var str = "I [have] strings that [are] like this";
var res = str.split(" ");
The result of res will be an array with the values:
I
[have]
strings
that
[are]
like
this
If you want to get only values between braces, you can use the following regex expression:
var str = "I [have] strings that [are] like this";
var result = [];
var pattern = /\[(.*?)\]/g;
var match;
while ((result = pattern.exec(str)) != null)
{
result.push(match[1]);
}
This is JSFiddle example for you.
Simple as this:
'I [have] strings that [are] like this.'.match(/\[([^\]]*)]/g)
Related
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 2 years ago.
Improve this question
I need help finding the string that matches specific patterns in an array of strings
For example
var array = ['hello there heretic', "purge the alien", "FOR THE EMPEROR!!" ]
How would I grab "FOR THE EMPEROR!!" if I want to find it by the following 2 separate scenarios:
Grab string in array which starts with "FOR"
Grab string in array that contains "EMPEROR"
They need to be ES5 or below though.
You can use the RegEx for checking the given string matching the requirements. Like this,
var regEx = /(^FOR)|(.*EMPEROR.*)/i;
var array = ['hello there heretic', "purge the alien", "FOR THE EMPEROR!!" ]
array.filter(function(str) { return regEx.test(str) }) // ["FOR THE EMPEROR!!"]
For case-sensitive remove i in regex like: /(^FOR)|(.*EMPEROR.*)/
var regEx = /(^FOR)|(.*EMPEROR.*)/i;
var array = ['hello there heretic', "purge the alien", "FOR THE EMPEROR!!", "For the champion", "And the EMPEROR" ]
const result = array.filter(function(str) { return regEx.test(str) })
console.log({result})
If you need to support lower version of IE, use indexOf instead of
includes.
let array = ['hello there heretic', "purge the alien", "FOR THE EMPEROR!!"];
console.log(array.filter( function(el) {
return el.indexOf("EMPEROR") > -1 && el.split(" ")[0] == "FOR"
}))
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I wrote a small function to split a string stored in variable data,
var data = "Apple|Banana";
var _res = data.split('|');
After printing _res on the console, it is Printing as Apple,Banana.
I am looking for an output where each String is printed on a newline, like,
Apple
Banana
your variable _res is an Array because it was created after splitting data. Hence it is getting printed as it is.
If you want a newline print, you need to manually do it. See below Code as an example.
Use case when you want to iterate over your input:
var data = 'Apple|Banana'; //Assuming your data variable
var _res = data.split('|');
_res.forEach(function(element) {
console.log(element);
});
Use case when you just want to test in console and alert:
var data = 'Apple|Banana'; //Assuming your data variable
var _res = data.split('|').join('\n');
alert(_res);
console.log(_res);
It sounds like you want the output as a string, in which case you shouldn't use split (which returns an array), but .replace - replace all |s with newlines:
const res = 'Apple|Banana'.replace(/\|/g, '\n');
console.log(res);
Or, with alert:
const res = 'Apple|Banana'.replace(/\|/g, '\n');
alert(res);
You should check Escape notation. You can encode special character which will have special meaning in string.
\n is used to create line breaks in string.You can split() string by , and join() by \n.
let str = 'Apple,Banana'
let newStr = str.split(',').join('\n')
console.log(newStr);
let str = 'Apple,Banana'
document.querySelector('div').innerHTML = str.split(',').join('<br>')
<div><div>
If my understanding to your problem is correct, you want to split the string using "|" and "," characters. In that case you can use pass regex value in your split method parameter.
var _res = d.data.split(/[,|]+/);
You can use this site to generate your regex https://www.regextester.com/
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'));
This question already has answers here:
How do you access the matched groups in a JavaScript regular expression?
(23 answers)
Closed 8 years ago.
I got text like: do[A]and[B]
I want to extract all words that are wrapped by [ and ].
I am using the match method:
var text = "do[A]and[B]";
var regexp = /\[(\w+)\]/g;
var result = text.match(regexp);
So I am saying that I want to match all words wrapped by [ ], but only the wrapped part should be in group/memory. I keep getting the [ ] parentheses in result:
["[A]", "[B]"]
expected result is:
["A","B"]
I thought this is a piece of cake to do, but I must be missing something.
For this particular case you don't need capturing groups:
>>> "do[A]and[Bbbb]".match(/\w+(?=])/g);
["A", "Bbbb"]
will do.
In order to work with subpatterns, there is no easy shortcut.
Instead, you have to repeatedly execute the regex on the string and collect the subpattern you want. Something like this:
var text = "do[A]and[B]",
regexp = /\[(\w+)\]/g,
result = [], match;
while(match = regexp.exec(text)) {
result.push(match[1]);
}