I'm trying to extract some data from a large string and I was wondering if it is possible to use regexp. Currently, I'm using javascript. For example:
This is some [example] text for my javascript [regexp] [lack] of knowledge.
With this string, I would like to generate a JSON array with the texts that are between the square brackets.
example, regexp, lack
I hope someone can help me do this in a simple way so I can understand how it works. Thank you in advance for your help. Daniel!
var str = "This is some [example] text for my javascript [regexp] [lack] of knowledge."
var regex = /\[(.*?)\]/g, result, indices = [];
while ( (result = regex.exec(str)) ) {
indices.push(result[1]);
}
var text = 'some [example] text for my javascript [regexp] [lack] of knowledge.';
text.match(/\[(.*?)\]/g).map(function(m) {
return m.substr(1, m.length - 2);
})
// => ["example", "regexp", "lack"]
http://jsfiddle.net/mE7EQ/
I wrote one up real quick, if you have any questions about it, let me know!
var a = 'This is some [example] text for my javascript [regexp] [lack] of knowledge.'
var results = a.match(/\[\w*\]/g);
alert(results[0] + ' ' + results[1] + ' ' + results[2]);
Related
When making a fetch to a certain URL, I am getting an HTML page in the format of text as I wanted.
Inside of it, there are plenty of id=(...)" and I require one of them
So I am asking, how could I get an array with all the strings that come after "id=" and before the " " "?
I made some tries such as :
var startsWith = "id="
var endsWith = "\""
var between = fullString.slice(fullString.indexOf(startsWith), fullstring.indexOf(endsWith))
but couldn't get it to work.
Any suggestions are welcome
you can use the following regex: /id=\"(.*?)\"/gmi.
The code will be as such:
fullString.match(/id=\"(.*?)\"/gmi)
The result will be an array of id="your id"
and then you can do the following:
var between = fullString.match(/id=\"(.*?)\"/gmi).map(str => str.substr(str.indexOf('id=\"') + 'id=\"'.length).slice(0, -1))
Why you dont use a plugin like jquery? Please refer to this example:
var fullString = "<y>your cool html</y>";
var $html = $(fullString);
var stuffInside = $(html).find('#yourId');
console.warn('stuffInside:', stuffInside.html());
I need a algorithm which is doing something like this:
var example = "Hello $$user$$ your real name is $$realname$$. Have a good day"
Output --> ["Hello ", "$$user$$", " your real name is ", "$$realname$$", ". Have a good day"]
Hence, split the part by a selected character and put them together in a string array. Can someone help me out?
I'm looking for a solution with JavaScript/jQuery
It seems you want to split by pattern $$...$$; You could use /(\$\$.*?\$\$)/; To keep the pattern in the result, you can make it a capture group, and also make it lazy (?) so that it will split with the shortest length pattern matched:
example.split(/(\$\$.*?\$\$)/)
#[ 'Hello ',
# '$$user$$',
# ' your real name is ',
# '$$realname$$',
# '. Have a good day' ]
Yes, this is possible with JavaScript itself... Slightly tricky, but yes.
var strings = [], tokens = [];
var str = "Hello $$user$$ your real name is $$realname$$. Have a good day".replace(/\$\$(.*?)\$\$/g, "\$\$TOKEN$1\$\$").split("$");
for (var i = 0; i < str.length; i++) {
if (str[i].indexOf("TOKEN") === 0) {
// This is a token.
tokens.push(str[i].replace("TOKEN", ""));
} else {
strings.push(str[i]);
}
}
str = str.map(function (v) {
if (v.indexOf("TOKEN") === 0)
return "$$" + v.replace("TOKEN", "") + "$$";
return v;
});
console.log(str);
console.log(strings);
console.log(tokens);
The above code will split everything into tokens. And on top of it, it also separates the strings and tokens out. The above one gives as per your requirement:
[
"Hello ",
"$$user$$",
" your real name is ",
"$$realname$$",
". Have a good day"
]
Kindly note, there's nothing like {value, value}, there's only [value, value].
String.split()
The split() method splits a String object into an array of strings by separating the string into substrings.
var example = "Hello $$user$$ your real name is $$realname$$. Have a good day";
var exSplit = example.split("$$");
var userIdx = exSplit.indexOf("user");
var nameIdx = exSplit.indexOf("realname");
document.querySelector(".user").innerHTML = exSplit[userIdx];
document.querySelector(".name").innerHTML = exSplit[nameIdx];
<div class="user"></div>
<div class="name"></div>
Though, if I may suggest, variables can handle this type of operation without all of the hassle.
I was wondering if there is a safe way (if the data is coming from users) to get the string and the number separated - for example "something-55", "something-124", "something-1291293"
I would want:
something and
55
something and
124
something and
1291293
I mean by a 'safe way' is to be certain I am getting only the number on the end.. if the data is coming from the users "something" could be anything some-thing-55 for example..
I'm looking for a robust way.
try this, working.
var string = 'something-456';
var array = string.split('-');
for (var i = 0;i<array.length;i++){
var number = parseFloat(array[i]);
if(!isNaN(number)){
var myNumber = number;
var mySomething = array[i - 1];
console.log('myNumber= ' + myNumber);
console.log('mySomething= ' + mySomething);
}
}
Can you try this?
var input='whatever-you-want-to-parse-324';
var sections=input.split(/[\w]+-/);
alert(sections[sections.length-1]);
You can use substr along with lastIndexOf:
var str = "something-somethingelse-55",
text = str.substr(0, str.lastIndexOf('-')),
number = str.substr(str.lastIndexOf('-') + 1);
console.log(text + " and " + number);
Fiddle Demo
All though it's a tad late, this would be the most restrictive solution:
var regex = /^([-\w])+?-(\d+)$/,
text = "foo-123",
match = test.match(regex);
You will get a match object back with the following values:
[ "foo-123", "foo", "123" ]
It's a very strict match so that " foo-123" and "foo-123 " would not match, and it requires the string to end in one or more digits.
Admittedly I'm terrible with RegEx and pattern replacements, so I'm wondering if anyone can help me out with this one as I've been trying now for a few hours and in the process of pulling my hair out.
Examples:
sum(Sales) needs to be converted to Sales_sum
max(Sales) needs to be converted to Sales_max
min(Revenue) needs to be converted to Revenue_min
The only available prefixed words will be sum, min, max, avg, xcount - not sure if this makes a difference in the solution.
Hopefully that's enough information to kind of show what I'm trying to do. Is this possible via RegEx?
Thanks in advance.
There are a few possible ways, for example :
var str = "min(Revenue)";
var arr = str.match(/([^(]+)\(([^)]+)/);
var result = arr[2]+'_'+arr[1];
result is then "Revenue_min".
Here's a more complex example following your comment, handling many matches and lowercasing the verb :
var str = "SUM(Sales) + MIN(Revenue)";
var result = str.replace(/\b([^()]+)\(([^()]+)\)/g, function(_,a,b){
return b+'_'+a.toLowerCase()
});
Result : "Sales_sum + Revenue_min"
Try with:
var input = 'sum(Sales)',
matches = input.match(/^([^(]*)\(([^)]*)/),
output = matches[2] + '_' + matches[1];
console.log(output); // Sales_sum
Also:
var input = 'sum(Sales)',
output = input.replace(/^([^(]*)\(([^)]*)\)/, '$2_$1');
You can use replace with tokens:
'sum(Sales)'.replace(/(\w+)\((\w+)\)/, '$2_$1')
Using a whitelist for your list of prefixed words:
output = input.replace(/\b(sum|min|max|avg|xcount)\((.*?)\)/gi,function(_,a,b) {
return b.toLowerCase()+"_"+a;
});
Added \b, a word boundary. This prevents something like "haxcount(xorz)" from becoming "haxorz_xcount"
I know this has been answered before, but I'm a newb and I can't get it to work in my situation. Basically, I have pages that call the URL and display part of them on the page. I am hoping to have the first letter of the displayed word capitalize automatically.
This is an example of what i'm using:
<script>
var str = (window.location.pathname);
var str2 = "/seedling/";
document.write(str.substr(str2.length,(str.length - str2.length - 1 ) ) );
</script>
Thanks so much for your help, it is much appreciated!!
You can capitalise the first letter of a string like this:
var capitalised = yourString.charAt(0).toUpperCase() + yourString.slice(1);
Alternatively:
var capitalised = yourString.charAt(0).toUpperCase() + yourString.substring(1);
Assuming that your document.write call contains the string you want to capitalise:
var yourString = str.substr(str2.length,(str.length - str2.length - 1 ) );
var capitalised = yourString.charAt(0).toUpperCase() + yourString.slice(1);
If you have LoDash on hand, this can also be achieved using _.capitalize
_.capitalize('FRED');
// => 'Fred'