Find a (substring) inside a string - javascript

I'm working on a search function that can show partial result according to your search variable.
For example we are looking for a word "abcde".
We have records of strings like
"ioqwepasaea" "uhabcsdwe" "ewqabcde" "abcfeqs" "cdeeqwee"
So the results should show "uh*abc*sdwe" - "ewq*abcde*"- "*abc*feqs" - "*cde*eqwee"
Is this possible using Jquery? Thank you in advance!!!

Searching for substrings inside strings is done by using regular expressions.
Regular expressions (RegEx) can be used in javascript as well as other languages. It's universal.
RegEx is broadly used for datavalidation but can be used for searching for substrings as well.
There is a lot of guides on the internet on this topic.
I found one for you. take a look :)
http://www.javascriptkit.com/javatutors/re.shtml

As I understand your question, You want to search relating string to your database or etc. You can do it this so many ways. But "jQuery String Functions" are very helpful your solution and also look at Regular Expression. Please try it code below for inspiration related to "string functions".
var myRecords:Array = ["xjavascriptfasf","cavascript","abascript"];
var searchValue = "javascript";
for(var i =0; i<myRecords.length; i++) {
console.log(myRecords[i].search(searchValue));
}
output should be like this :
1
-1
-1
Thats means in your database and user search matched and returned it correct string.
Also please take a look at this "jquery string functions" http://www.jquerybyexample.net/2012/06/jquery-string-functions.html
I hope this is help your trouble.

Related

Get an example matched text from a regex pattern [duplicate]

Is there any way of generating random text which satisfies provided regular expression.
I am looking for a function which works like below
var reg = Some Regular Expression
var str = RandString(reg)
I have seen fairly good solutions in perl and ruby on github, but I think there are technical issues that make a complete solution impossible. For example, /[0-9]+/ has an infinite upper bound, which is not practical for selecting random numbers from.
Never seen it in JavaScript, but you could translate.
EDIT: After googling for a few seconds...
https://github.com/fent/randexp.js
if you know what the regular expression is, you can just generate random strings, then use a function that references the index of the letters and changes them as needed. Regex expressions vary widely, so it will be difficult to find one in particular that satisfies all possible regex.
Your question is pretty open so hopefully this steers you to the right solution. Get the current time (in seconds), MD5 it, check it against a REGEX, return the match.
Running Example: http://jsfiddle.net/MattLo/3gKrb/
Usage: RandString(/([A-Za-z])/ig); // expected to be a string
For JavaScript, the following modules can generate a random match to a regex:
pxeger
randexp.js
regexgen

regular expression to split string avoiding double tokens

In order to split a string value into an array using javascript I need to split using delimiters. Repeated delimiters indicate a sub-value within the array, so for example
abc+!+;def+!+!+;123+!+;xyz
should split into abc, [def, 123], xyz
My nearest expression is ((?:+!(?!+!))+\;|$) but thinking about it that may be the one I first started with, as I've gone through so many many variations since then.
There is probably a blindingly obvious answer, but after what seems an eternity I'm now stumped. I took a look at regex to parse string with escaped characters, and similar articles which were close although not the same problem, but basically came to a stop with ideas.
Somewhere out there someone will know regular expressions far better than I do, and hope that they have an answer
I got this to work by using .split() with this basic pattern:
\b\+!\+;\b
And then:
\b\+!\+!\+;\b
And so on, and so forth. You will need to turn this into a recursive function, but I made a basic JSFiddle to get you started. First we split the string using our first expression. Then we create our newer expression by adding !\+ (this can easily be done dynamically). Now we can loop through our initial array, see if the string matches our new expression and if it does split it again.
var string = 'abc+!+;def+!+!+;123+!+;xyz',
data = string.split(/\b\+!\+;\b/);
var regex = /\b\+!\+!\+;\b/
for(var i = 0; i < data.length; i++) {
var string = data[i];
if(string.match(regex)) {
data[i] = string.split(regex);
}
}
console.log(data);
// ["abc", ["def", "123"], "xyz"]
I'm leaving the task of making this a recursive function up to OP. If you want some direction, I can try to provide some more insight.

Regex not detecting swear words inside string?

I have a script here:
http://jsfiddle.net/d2rcx/
It has an array of badWords to compare input strings with.
This script works fine if the input string matches exactly as the swear word string but it does not pick up any variations where there is more characters in the string e.g. whitespace before the swear word.
Using this site as reference : http://www.zytrax.com/tech/web/regex.htm
It said the following regex would detect a string within a string.
var regex = new RegExp("/" + badWords[i] + "/g");
if (fieldValue.match(regex) == true)
return true;
However that does not seem to be the case.
What do I need to change to the regex to make it work.
Thanks
Also any good links to explain Regex than what google turns up would be appreciated.
Here's a corrected JSFiddle:
http://jsfiddle.net/d2rcx/5/
See the following documentation for RegExp:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp
Note that the second parameter is where you should specify your flags (e.g. 'g' or 'i'). For example:
new RegExp(badWords[i], 'gi');
Please review http://www.w3schools.com/jsref/jsref_match.asp and note that fieldValue.match() will not return a boolean but an array of matches
Rather than using Regex to do this you are probably better off just looping through an array of badwords and looking for instances within a string using [indexOf].(https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/indexOf)
Otherwise you could make a regex like...
\badword1|badword2|badword3\
and just check for any match.
A word boundary in Regex is \b so you could say
\\b(badword1|badword2|badword3)\b\
which will match only whole words - ie Scunthorpe will be ok :)
var rx = new RegExp("\\b(donkey|twerp|idiot)\\b","i"); // i = case insenstive option
alert(rx.test('you are a twerp')); //true
alert(rx.test('hello idiotstick')); //fasle -not whole word
alert(rx.test('nice "donkey"')); //true
http://jsfiddle.net/F8svC/
Changing this, which requires a loop:
var regex = new RegExp("/" + badWords[i] + "/g");
for this:
var regex = new RegExp("/" + badWords.join("|") + "/g");
would be a start. This will do all the matches in one go because the array becomes one string with each element separated by pipes.
P.S.
Reference guide for RegEx here. But there isn't a lot of clear information online about what is and isn't possible with respect to certain functions nor what's good code. I've found a couple of books most useful: David Flanagan's latest JavaScript: The Definitive Guide and Douglas Crockford's JavaScript: The Good Parts for the most usable subset of JavaScript, including RegEx. The railroad diagrams by Crockford are especially good but I'm not sure if they're available online anywhere.
EDIT: Here's an online copy of the relevant chapter including some of those railroad diagrams I mentioned, in case it helps.

How can I get wanted part from string with regular expression

I have a string like #'test'
and I have to get only test word without #' '
how can I match them with regular expression at javascript?
try the regex below:
#\'([^']*)\'
get group(1)
and if your language supports look-behind,( e.g. python, perl, java...):
(?<=#\')[^']*
should work too without grouping.
oh, just saw you edit your question, as far as I know, js doesn't support look-behind, then you could take the option 1.
var firsName= "#'test'"
var objName = firsName .replace('#', "'");
lastName=objName.replace(/[']/g,'');
I fixed it like that. I dont know is it best way or not. thanks for helping

Capture every URL in text [duplicate]

I have to find the first url in the text with a regular expression:
for example:
I love this website:http://www.youtube.com/music it's fantastic
or
[ es. http://www.youtube.com/music] text
I looked into this issue last year and developed a solution that you may want to look at - See: URL Linkification (HTTP/FTP) This link is a test page for the Javascript solution with many examples of difficult-to-linkify URLs.
My regex solution, written for both PHP and Javascript - is not simple (but neither is the problem as it turns out.) For more information I would recommend also reading:
The Problem With URLs by Jeff Atwood, and
An Improved Liberal, Accurate Regex Pattern for Matching URLs by John Gruber
The comments following Jeff's blog post are a must read if you want to do this right...
Note that this question gets asked a lot. Maybe do a search next time :)
You can't do this perfectly with a regular expression. You may be interested in this blog post. There is a bit more information on Regex Guru, but even those look very fragile. You will need to have additional checks outside of your regular expression to catch the edge cases.
Identifying URLs is tricky because they are often surrounded by punctuation marks and because users frequently do not use the full form of the URL. Many JavaScript functions exist for replacing URLs with hyperlinks, but I was unable to find one that works as well as the urlize filter in the Python-based web framework Django. I therefore ported Django's urlize function to JavaScript: https://github.com/ljosa/urlize.js
It actually would not pick up the URL in your example because there is a colon right before the URL. But if we modify the example a little:
urlize("I love this website: http://www.youtube.com/music it's fantastic", true, true)
=> 'I love this website: http://www.youtube.com/music it's fantastic"'
Note the second argument which, if true, inserts rel="nofollow" and the third argument which, if true, quotes characters that have special meaning in HTML.
This might work->
\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))
Found it somewhere
Will find links ->
http://foo.com/blah_blah/
(Something like http://foo.com/blah_blah)
http://foo.com/blah_blah_(wikipedia)
Hope this works....
i am using this regex : :) ( its translated ABNF )
[a-zA-Z]([a-zA-Z]|[0-9]|\+|\-|\.)*:\/\/((([a-zA-Z]|[0-9]|-|\.|_|~)|%[0-9A-Fa-f][0-9A-Fa-f]|[!$&'\(\)\*\+,;=]|:)*#)?(\[((([0-9A-Fa-f]{1,4}:){6}([0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}|(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.(25[0-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][0-9A-Fa-f]|[!$&'\(\)\*\+,;=])*)(:[0-9]*)?(((\/(([a-zA-Z]|[0-9]|-|\.|_|~)|%[0-9A-Fa-f][0-9A-Fa-f]|[!$&'\(\)\*\+,;=]|:|#)*)*|\/((([a-zA-Z]|[0-9]|-|\.|_|~)|%[0-9A-Fa-f][0-9A-Fa-f]|[!$&'\(\)\*\+,;=]|:|#){1}(\/(([a-zA-Z]|[0-9]|-|\.|_|~)|%[0-9A-Fa-f][0-9A-Fa-f]|[!$&'\(\)\*\+,;=]|:|#)*)*)?|(([a-zA-Z]|[0-9]|-|\.|_|~)|%[0-9A-Fa-f][0-9A-Fa-f]|[!$&'\(\)\*\+,;=]|:|#){1}(\/(([a-zA-Z]|[0-9]|-|\.|_|~)|%[0-9A-Fa-f][0-9A-Fa-f]|[!$&'\(\)\*\+,;=]|:|#)*)*|(([a-zA-Z]|[0-9]|-|\.|_|~)|%[0-9A-Fa-f][0-9A-Fa-f]|[!$&'\(\)\*\+,;=]|#){1}(\/(([a-zA-Z]|[0-9]|-|\.|_|~)|%[0-9A-Fa-f][0-9A-Fa-f]|[!$&'\(\)\*\+,;=]|:|#)*)*))?\/?(\?((([a-zA-Z]|[0-9]|-|\.|_|~)|%[0-9A-Fa-f][0-9A-Fa-f]|[!$&'\(\)\*\+,;=]|:|#)|\/|\?)*)?(\#((([a-zA-Z]|[0-9]|-|\.|_|~)|%[0-9A-Fa-f][0-9A-Fa-f]|[!$&'\(\)\*\+,;=]|:|#)|\/|\?)*)?
You can use the following regex expression for extracting any type of url coming in message.
String regex = "(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&/=]*)";
Typescript/Angular
This works for me:
const regExpressionUrl = new RegExp(/(https?:\/\/[^\s]+)/g); //detect URL
Ref: https://www.regextester.com/96249%7CRegular

Categories

Resources