How can I find a word with regular expression in Javascript?
For example:
http://127.0.0.1/w/?id=2&tab=wow
I want to know if this link contains the word 'tab'.
var string = 'http://127.0.0.1/w/?id=2&tab=wow'
var containsTab = string.indexOf('tab') > -1
Or if you really want to use a regex:
var containsTab = string.match(/tab/);
jQuery is not a language. It's a library written for JavaScript.
You don't need a regular expression.
Use indexOf.
var str = 'http://127.0.0.1/w/?id=2&tab=wow';
if(str.indexOf('tab') > -1) {
// Contains string
} else {
// Doesn't
}
Related
I have written a node module with several places that use regular expressions to limit which files are manipulated as below:
if (!file.match(/\/node_modules\//) && !file.match(/\/fontawesome\//) && !file.match(/\/docs\//) && !file.match(/\/target\//) && !seenFile[file]) {
//do some processing
}
I'm trying to modify the module to accept user input as an array - i.e.:
['/node_modules/', '/fontawesome/', '/docs/', '/target/']
Is there a good way to convert the array into the regex? I know apply might work if I wasn't using file.match but I'm not sure if it will work in this instance. Thanks in advance.
You can use the array of values to build a dynamic regex:
Escape all special regex characters with .replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
Build the regex with the help of | alternation operator
Use the regex with String#match or RegExp#exec methods.
Here is a working snippet:
var ar = ['/node_modules/', '/fontawesome/', '/docs/', '/target/'];
ar = ar.map(function(item) {
return item.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
});
var rx = RegExp(ar.join("|"));
var file = "/node_modules/d.jpg";
if (!file.match(rx)) {
console.log("No stop words found!");
} else {
console.log("Stop words found!");
}
In Javascript, how do I determine if some specific HTML is contained within a larger hunk of HTML?
I tried regex:
var htmlstr;
var reg = /<b class="fl_r">Example</b>/.test(htmlstr);
but it doesn't work! Console outputs "missing /". Please, help me fix this.
Regex is a bit of an overkill here. You can just use indexOf like this and not have to worry about escaping things in the string:
var htmlstr1 = 'foo';
var htmlstr2 = 'some stuff <b class="fl_r">Example</b> more stuff';
if (htmlstr1.indexOf('<b class="fl_r">Example</b>') != -1) {
alert("found match in htmlstr1");
}
if (htmlstr2.indexOf('<b class="fl_r">Example</b>') != -1) {
alert("found match in htmlstr2");
}
jsFiddle to play with it is here: http://jsfiddle.net/jfriend00/86Kny/
You need to escape the / character.
Try:
var htmlstr = '<b class="fl_r">Example</b>';
var reg = /<b class="fl_r">Example<\/b>/.test(htmlstr);
Example # http://jsfiddle.net/7cuKe/2/
I have a string like
var test="ALL,l,1,2,3";
How to remove ALL from string if it contains using javascript.
Regards,
Raj
you can use js replace() function:
http://www.w3schools.com/jsref/jsref_replace.asp
so:
test.replace("ALL,", "");
If the word All can appear anywhere or more than once (e.g. "l,1,ALL,2,3,ALL") then have such code:
var test = "l,1,ALL,2,3,ALL"
var parts = test.split(",");
var clean = [];
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
if (part !== "ALL")
clean.push(part);
}
var newTest = clean.join(",");
After this the variable newTest will hold the string without ALL.
If all you want to do is remove occurrences of the string "ALL" from another string, you can use the JavaScript String object's replace method:
test.replace("ALL","");
I'm not really sure if you want to remove all instances of capital letters from your string, but you are probably looking at using a regular expression such as s.replace(/[A-Z]/g,"") where s is the string.
Looking up javascript RegExp will give more indepth details.
use:
test.replace ( 'ALL,', '' );
My Text
1618148163###JASSER-PC#-#1125015374###anas kayyat#-#1543243035###anas kayyat#-#
Result Should Be:
JASSER-PC
anas kayyat
anas kayyat
I am using :
(?<=###)(.+)(?=#-#)
But it gives me that :
JASSER-PC#-#1125015374###anas kayyat#-#1543243035###anas kayyat
JavaScript’s regular expressions don’t support look-behind assertions (i.e. (?<=…) and (?<!…)), so you can’t use that regular expression. But you can use this:
###(.+)(?=#-#)
Then just take the matched string of the first group. Additionally, to only match as little as possible, make the + quantifier non-greedy by using +?.
The group (.+) will match as much as it can (it's "greedy"). To make it find a minimal match you can use (.+?).
JavaScript does not support lookbehinds. Make the quantifier non greedy, and use:
var regex = /###(.+?)#-#/g;
var strings = [];
var result;
while ((result = regex.exec(input)) != null) {
strings.push(result[1]);
}
I'll give you a non-regex answer, since using regular expressions isn't always appropriate, be it speed or readibility of the regex itself:
function getText(text) {
var arr = text.split("###"); // arr now contains [1618148163,JASSER-PC#-#1125015374,anas kayyat#-#1543243035,anas kayyat#-#]
var newarr = [];
for(var i = 0; i < arr.length; i++) {
var index = arr[i].indexOf("#-#");
if(index != -1) { // if an array element doesn't contain "#-#", we ignore it
newarr.push(arr[i].substring(0, index));
}
}
return newarr;
}
Now, using
getText("1618148163###JASSER-PC#-#1125015374###anas kayyat#-#1543243035###anas kayyat#-#");
returns what you wanted.
Struggling with a regex requirement. I need to split a string into an array wherever it finds a forward slash. But not if the forward slash is preceded by an escape.
Eg, if I have this string:
hello/world
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = world
And if I have this string:
hello/wo\/rld
I would like it to be split into an array like so:
arrayName[0] = hello
arrayName[1] = wo/rld
Any ideas?
I wouldn't use split() for this job. It's much easier to match the path components themselves, rather than the delimiters. For example:
var subject = 'hello/wo\\/rld';
var regex = /(?:[^\/\\]+|\\.)+/g;
var matched = null;
while (matched = regex.exec(subject)) {
print(matched[0]);
}
output:
hello
wo\/rld
test it at ideone.com
The following is a little long-winded but will work, and avoids the problem with IE's broken split implementation by not using a regular expression.
function splitPath(str) {
var rawParts = str.split("/"), parts = [];
for (var i = 0, len = rawParts.length, part; i < len; ++i) {
part = "";
while (rawParts[i].slice(-1) == "\\") {
part += rawParts[i++].slice(0, -1) + "/";
}
parts.push(part + rawParts[i]);
}
return parts;
}
var str = "hello/world\\/foo/bar";
alert( splitPath(str).join(",") );
Here's a way adapted from the techniques in this blog post:
var str = "Testing/one\\/two\\/three";
var result = str.replace(/(\\)?\//g, function($0, $1){
return $1 ? '/' : '[****]';
}).split('[****]');
Live example
Given:
Testing/one\/two\/three
The result is:
[0]: Testing
[1]: one/two/three
That first uses the simple "fake" lookbehind to replace / with [****] and to replace \/ with /, then splits on the [****] value. (Obviously, replace [****] with anything that won't be in the string.)
/*
If you are getting your string from an ajax response or a data base query,
that is, the string has not been interpreted by javascript,
you can match character sequences that either have no slash or have escaped slashes.
If you are defining the string in a script, escape the escapes and strip them after the match.
*/
var s='hello/wor\\/ld';
s=s.match(/(([^\/]*(\\\/)+)([^\/]*)+|([^\/]+))/g) || [s];
alert(s.join('\n'))
s.join('\n').replace(/\\/g,'')
/* returned value: (String)
hello
wor/ld
*/
Here's an example at rubular.com
For short code, you can use reverse to simulate negative lookbehind
function reverse(s){
return s.split('').reverse().join('');
}
var parts = reverse(myString).split(/[/](?!\\(?:\\\\)*(?:[^\\]|$))/g).reverse();
for (var i = parts.length; --i >= 0;) { parts[i] = reverse(parts[i]); }
but to be efficient, it's probably better to split on /[/]/ and then walk the array and rejoin elements that have an escape at the end.
Something like this may take care of it for you.
var str = "/hello/wo\\/rld/";
var split = str.replace(/^\/|\\?\/|\/$/g, function(match) {
if (match.indexOf('\\') == -1) {
return '\x00';
}
return match;
}).split('\x00');
alert(split);