i'm trying to get the first word after a determined word, that's how i'm doing:
Text:
Companie: 'Stack over flow';
Regex:
var reg = new RegExp('Companie' + '.*?(\\w\\S*)', 'i');
var match = reg.exec(text);
The output will be:
'Stack'.
I want receive all the name, but this name is dinamically, sometimes there are just one word, sometime 5, sometime 2.. etc
Possible?
Thanks.
I'd say that isn't a scenario where a regex should be used, but something like this instead:
var str = 'Companie: Stack over flow';
var name = str.split('Companie:')[1].trim();
alert(name);
michael has a good answer, but if you want a regex for that, you can go with
var text = "Companie: 'Stack over flow';"
var reg = /^Companie: '(.*)';$/
var match = reg.exec(text)[1];
The value of match is
"Stack over flow"
Related
In my Javascript code, I get one very long line as a string.
This one line only has around 65'000 letters. Example:
config=123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...
What I have to do is replace all & with an break (\n) first and then pick only the line which starts with "path_of_code=". This line I have to write in a variable.
The part with replace & with an break (\n) I already get it, but the second task I didn't.
var obj = document.getElementById('div_content');
var contentJS= obj.value;
var splittedResult;
splittedResult = contentJS.replace(/&/g, '\n');
What is the fastest way to do it? Please note, the list is usually very long.
It sounds like you want to extract the text after &path_of_code= up until either the end of the string or the next &. That's easily done with a regular expression using a capture group, then using the value of that capture group:
var rex = /&path_of_code=([^&]+)/;
var match = rex.exec(theString);
if (match) {
var text = match[1];
}
Live Example:
var theString = "config=123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...";
var rex = /&path_of_code=([^&]+)/;
var match = rex.exec(theString);
if (match) {
var text = match[1];
console.log(text);
}
Use combination of String.indexOf() and String.substr()
var contentJS= "123&url=http://localhost/example&path_of_code=blablaba&link=kjslfdjs...";
var index = contentJS.indexOf("&path_of_code"),
substr = contentJS.substr(index+1),
res = substr.substr(0, substr.indexOf("&"));
console.log(res)
but the second task I didn't.
You can use filter() and startsWith()
splittedResult = splittedResult.filter(i => i.startsWith('path_of_code='));
I have a requirement where there is a customet name text box and the user able to input customer name to search customer. And the condition is user can add do wild card search putting * either infront or after the customer name. And the customer name should be minimum three characters long. I am using Regex to validate the user entry.
Now in case the input is like "*aaa*" .. I am validate this type of input using the following regex :
[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}
The code is like below:
var str = "*aaa*";
var patt = new RegExp("[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}");
var res = patt.test(str);
alert(res);
var str = "*aaa***";
var patt = new RegExp("[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}");
var res = patt.test(str);
alert(res);
var str = "*aaa*$$$$";
var patt = new RegExp("[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}");
var res = patt.test(str);
alert(res);
Now for the input "*aaa*" res is coming true. But for this type of inputs also "*aaa**", "*aaa*$" its comimg true. And this expected as these expressions also contains the part( *aaa*) which satisfies the regex.But these inputs("*aaa**", *aaa*$** etc. ) are wrong.
Please let me know where I am doing wrong ? is there any issue with the regex or the way checking is wrong ?
^(?:[*]([a-z]|[A-Z]|[0-9]){3,}[*])$
Use anchors ^$ to disable partial matching.See demo.
https://regex101.com/r/tS1hW2/17
The string *aaa*$$$ contains a segment of *aaa*, so it will yield true; to match against the whole string you need to add anchors on both sides. The $ and ^ anchors assert the start and end of the subject respectively.
Also, you can simply the expression greatly by using a character class trick. The \w is comprised of [0-9a-zA-Z_], and we only don't want the underscore, so we can use a negative character class with the opposite of \w (which is \W) and an underscore; I agree, it takes some mental power ;-)
var str = "*aaa*$";
var patt = /^\*[^\W_]{3,}\*$/;
var res = patt.test(str);
alert(res); // false
Alternatively, you can merge all your character classes together into one like so:
[A-Za-z0-9]
I am using the function match for a search engine, so whenever a user types a search-string I take that string and use the match function on an array containing country names, but it doesn't seem to work.
For example if I do :
var string = "algeria";
var res = string.match(/alge/g); //alge is what the user would have typed in the search bar
alert(res);
I get a string res = "alge": //thus verifying that alge exists in algeria
But if I do this, it returns null, why? and how can I make it work?
var regex = "/alge/g";
var string = "algeria";
var res = string.match(regex);
alert(res);
To make a regex from a string, you need to create a RegExp object:
var regex = new RegExp("alge", "g");
(Beware that unless your users will be typing actual regular expressions, you'll need to escape any characters that have special meaning within regular expressions - see Is there a RegExp.escape function in Javascript? for ways to do this.)
You don't need quotes around the regex:
var regex = /alge/g;
Remove the quotes around the regex.
var regex = /alge/g;
var string = "algeria";
var res = string.match(regex);
alert(res);
found the answer, the match function takes a regex object so have to do
var regex = new RegExp(string, "g");
var res = text.match(regex);
This works fine
I have a string like:
some people may work for some thing new.
I need to fetch the 2nd instance of the word 'some' using javascript reg exp.
how can i get that?
here is my try:
var text = "some people may work for some thing new";
var patt = /some/.test(text);
console.log(patt);
But I am getting simply 'true' in console. But I need to get the word to be consoled. ( even i may need to replace too).
any one help me?
You need to use .match with the regex, and also use the g flag for global
var text = "some people may work for some thing new";
var patt = /some/g;
var matches = text.match(patt);
console.log( matches );
console.log( matches[1] );
Will give you an array of all instances of the word some
var text = "some people may work for some thing new";
var patt = text.match(/some/g);
console.log(patt);
will give you all the instances of the word you want to find in the sentence.
Then you can simply use replace similarly.
Suppose you want to search and replace the second word some.
Then just see this question
In addition to that you can also do something like this:
function doit(str, tobereplaced, occurence, withwhat){
var res = str.split(tobereplaced);
console.log(res);
var foo = []
for (var i = 0; i < occurence; i++) {
foo.push(res[i]);
}
var bar = []
for (var j = occurence; j < res.length; j++) {
bar.push(res[i]);
}
return foo.join("")+withwhat+bar.join("");
}
var str = "ssfds some people may work for some thing new some thing again some again";
doit(str, "some", 2, "bomb");
You can use the match method of the string to get an array of all the occurrences:
text.match(/some/g)
You need the 'g' flag in the regex otherwise the match will stop after the first hit
Here is how you replace the 2nd instance:
'some people may work for some thing new.'.replace(/(\bsome\b.*?)\bsome\b/, "$1foo");
//=> some people may work for foo thing new.
use the function exec(text) instend of test(text)
replace your code:
var patt = /some/.test(text);
to:
var patt = /some/.exec(text);
From server I get data as such:
"07.00 PROGRAM DESCRIPTION"
"07.20 PROGRAM DESCRIPTION 2"
I want to split them into a 2 indexed array such as: ["07.00", "PROGRAM DESCRIPTION 2"]. Regular split( " " ) would not work me as the description part contains severaral " " spaces.
I will be grateful for any suggestion.
Regards
You could use:
var parts = str.split(' '),
time = parts.shift(),
description = parts.join(' ');
or, to get your array:
var parts = str.split(' ');
parts[1] = parts.slice(1).join(' ');
;)
You need somekind of a pattern, which is reliable. If it's always the case that you need to split just between the first whitespace character to you can do:
var blub = "07.00 PROGRAM DESCRIPTION",
pos = blub.indexOf(" "),
arr = [];
arr[0] = blub.slice(0, pos);
arr[1] = blub.slice(pos + 1);
or you might just want to use regular expression. Since I don't pretend to be a genius on that field here is my little suggestion:
var blub = "07.00 PROGRAM DESCRIPTION",
arr = /(\d+\.\d+)\s(.*)/.exec(blub);
var pattern = /([0-9]{2}\.[0-9]{2})\s(.+)/;
var data = "07.00 PROGRAM DESCRIPTION";
var parsed = pattern.exec(data);
console.log(parsed); // (Array) ["07.00 PROGRAM DESCRIPTION", "07.00", "PROGRAM DESCRIPTION"]
this is flexible and easier to adapt in case the format changes (just change the pattern and use that var anywhere else in your code)
The substring method:
var time = row.substring(0,4);
var description = row.substring(5);
Or, with the split method:
row = row.split(" ",1);
The second parameter is the maximum number of splits... so it'll only split at the first space. Edit: this won't work. Use the first method instead.