How can I get a substring located between 2 quotes? - javascript

I have a string that looks like this: "the word you need is 'hello' ".
What's the best way to put 'hello' (but without the quotes) into a javascript variable? I imagine that the way to do this is with regex (which I know very little about) ?
Any help appreciated!

Use match():
> var s = "the word you need is 'hello' ";
> s.match(/'([^']+)'/)[1];
"hello"
This will match a starting ', followed by anything except ', and then the closing ', storing everything in between in the first captured group.

http://jsfiddle.net/Bbh6P/
var mystring = "the word you need is 'hello'"
var matches = mystring.match(/\'(.*?)\'/); //returns array
​alert(matches[1]);​

If you want to avoid regular expressions then you can use .split("'") to split the string at single quotes , then use jquery.map() to return just the odd indexed substrings, ie. an array of all single-quoted substrings.
var str = "the word you need is 'hello'";
var singleQuoted = $.map(str.split("'"), function(substr, i) {
return (i % 2) ? substr : null;
});
DEMO
CAUTION
This and other methods will get it wrong if one or more apostrophes (same as single quote) appear in the original string.

Related

Regex trying to match characters before and after symbol

I'm trying to match characters before and after a symbol, in a string.
string: budgets-closed
To match the characters before the sign -, I do: ^[a-z]+
And to match the other characters, I try: \-(\w+) but, the problem is that my result is: -closed instead of closed.
Any ideas, how to fix it?
Update
This is the piece of code, where I was trying to apply the regex http://jsfiddle.net/trDFh/1/
I repeat: It's not that I don't want to use split; it's just I was really curious, and wanted to see, how can it be done the regex way. Hacking into things spirit
Update2
Well, using substring is a solution as well: http://jsfiddle.net/trDFh/2/ and is the one I chosed to use, since the if in question, is actually an else if in a more complex if syntax, and the chosen solutions seems to be the most fitted for now.
Use exec():
var result=/([^-]+)-([^-]+)/.exec(string);
result is an array, with result[1] being the first captured string and result[2] being the second captured string.
Live demo: http://jsfiddle.net/Pqntk/
I think you'll have to match that. You can use grouping to get what you need, though.
var str = 'budgets-closed';
var matches = str.match( /([a-z]+)-([a-z]+)/ );
var before = matches[1];
var after = matches[2];
For that specific string, you could also use
var str = 'budgets-closed';
var before = str.match( /^\b[a-z]+/ )[0];
var after = str.match( /\b[a-z]+$/ )[0];
I'm sure there are better ways, but the above methods do work.
If the symbol is specifically -, then this should work:
\b([^-]+)-([^-]+)\b
You match a boundry, any "not -" characters, a - and then more "not -" characters until the next word boundry.
Also, there is no need to escape a hyphen, it only holds special properties when between two other characters inside a character class.
edit: And here is a jsfiddle that demonstrates it does work.

Finding image url via using Regex

Any working Regex to find image url ?
Example :
var reg = /^url\(|url\(".*"\)|\)$/;
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
var string2 = 'url(http://domain.com/randompath/random4509324041123213.jpg)';
console.log(string.match(reg));
console.log(string2.match(reg));
I tied but fail with this reg
pattern will look like this, I just want image url between url(" ") or url( )
I just want to get output like http://domain.com/randompath/random4509324041123213.jpg
http://jsbin.com/ahewaq/1/edit
I'd simply use this expression:
/url.*\("?([^")]+)/
This returns an array, where the first index (0) contains the entire match, the second will be the url itself, like so:
'url("http://domain.com/randompath/random4509324041123213.jpg")'.match(/url.*\("?([^")]+)/)[1];
//returns "http://domain.com/randompath/random4509324041123213.jpg"
//or without the quotes, same return, same expression
'url(http://domain.com/randompath/random4509324041123213.jpg)'.match(/url.*\("?([^")]+)/)[1];
If there is a change that single and double quotes are used, you can simply replace all " by either '" or ['"], in this case:
/url.*\(["']?([^"')]+)/
Try this regexp:
var regex = /\burl\(\"?(.*?)\"?\)/;
var match = regex.exec(string);
console.log(match[1]);
The URL is captured in the first subgroup.
If the string will always be consistent, one option would be simply to remove the first 4 characters url(" and the last two "):
var string = 'url("http://domain.com/randompath/random4509324041123213.jpg")';
// Remove last two characters
string = string.substr(0, string.length - 2);
// Remove first five characters
string = string.substr(5, string.length);
Here's a working fiddle.
Benefit of this approach: You can edit it yourself, without asking StackOverflow to do it for you. RegEx is great, but if you don't know it, peppering your code with it makes for a frustrating refactor.

jQuery return first 5 words of a string without commas

I'm trying to return the first 5 words of a string in a readable format, no "" or commas separating words. I'm not sure if its a regex thing or what, but I can't figure it out although its probably simple. Thanks!
See what I have thus far:
http://jsfiddle.net/ccnokes/GktTd/
This is the function I'm using:
function getWords(string){
var words = string.split(/\s+/).slice(1,5);
return words;
}
The only thing you are missing is a join()
Try this:
function getWords(str) {
return str.split(/\s+/).slice(0,5).join(" ");
}
This will do something like:
var str = "This is a long string with more than 5 words.";
console.log(getWords(str)); // << outputs "This is a long string"
Take a look at this link for a further explanation of the .join(). function in javascript. Essentially - if you don't supply an argument, it uses the default delimiter ,, whereas if you supply one (as I'm doing in the above example, by providing " " - it will use that instead. This is why the output becomes the first 5 words, separated by a space between each.
Those commas are coming from how you output the data:
//write to DOM
$('<h2 />').text(getWords(str).join(' ')).appendTo('body');
​
When you add a string to getWords(str), javascript tries to convert the array into a string - it does this by joining the words with commas. If you want to join them with something else, use join.
Troy Alford solution is working, but is has one drawback. If between words there will be more than one space, or new line character (\n) it will be converted to single space, e.g:
'jQuery is a
multi-browser'
will be converted to
'jQuery is a multi-browser'
To fix this issue, we might use word boundary regex. It might looks like this:
function getFirstWords(text, wordsAmount) {
const arr = text.split(/\b/g);
const arrItemsAmount = (/\b/.exec(text) && /\b/.exec(text).index) ?
wordsAmount * 2 :
wordsAmount * 2 - 1;
return arr.slice(0, arrItemsAmount).join('');
}
You can do it with str.substring(1,15)

Extracting numbers from a string using regular expressions

I am clueless about regular expressions, but I know that they're the right tool for what I'm trying to do here: I'm trying to extract a numerical value from a string like this one:
approval=not requested^assignment_group=12345678901234567890123456789012^category=Test^contact_type=phone^
Ideally, I'd extract the following from it: 12345678901234567890123456789012 None of the regexes I've tried have worked. How can I get the value I want from this string?
This will get all the numbers:
var myValue = /\d+/.exec(myString)
mystr.match(/assignment_group=([^\^]+)/)[1]; //=> "12345678901234567890123456789012"
This will find everything from the end of "assignment_group=" up to the next caret ^ symbol.
Try something like this:
/\^assignment_group=(\d*)\^/
This will get the number for assignment_group.
var str = 'approval=not requested^assignment_group=12345678901234567890123456789012^category=Test^contact_type=phone^',
regex = /\^assignment_group=(\d*)\^/,
matches = str.match(regex),
id = matches !== null ? matches[1] : '';
console.log(id);
If there is no chance of there being numbers anywhere but when you need them, you could just do:
\d+
the \d matches digits, and the + says "match any number of whatever this follows"

Replace multiple whitespaces with single whitespace in JavaScript string

I have strings with extra whitespace characters. Each time there's more than one whitespace, I'd like it be only one. How can I do this using JavaScript?
Something like this:
var s = " a b c ";
console.log(
s.replace(/\s+/g, ' ')
)
You can augment String to implement these behaviors as methods, as in:
String.prototype.killWhiteSpace = function() {
return this.replace(/\s/g, '');
};
String.prototype.reduceWhiteSpace = function() {
return this.replace(/\s+/g, ' ');
};
This now enables you to use the following elegant forms to produce the strings you want:
"Get rid of my whitespaces.".killWhiteSpace();
"Get rid of my extra whitespaces".reduceWhiteSpace();
Here's a non-regex solution (just for fun):
var s = ' a b word word. word, wordword word ';
// with ES5:
s = s.split(' ').filter(function(n){ return n != '' }).join(' ');
console.log(s); // "a b word word. word, wordword word"
// or ES2015:
s = s.split(' ').filter(n => n).join(' ');
console.log(s); // "a b word word. word, wordword word"
Can even substitute filter(n => n) with .filter(String)
It splits the string by whitespaces, remove them all empty array items from the array (the ones which were more than a single space), and joins all the words again into a string, with a single whitespace in between them.
using a regular expression with the replace function does the trick:
string.replace(/\s/g, "")
I presume you're looking to strip spaces from the beginning and/or end of the string (rather than removing all spaces?
If that's the case, you'll need a regex like this:
mystring = mystring.replace(/(^\s+|\s+$)/g,' ');
This will remove all spaces from the beginning or end of the string. If you only want to trim spaces from the end, then the regex would look like this instead:
mystring = mystring.replace(/\s+$/g,' ');
Hope that helps.
jQuery.trim() works well.
http://api.jquery.com/jQuery.trim/
I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:
I want to replace multiple occurences of whitespace inside the string with a single space
...and... I do not want whitespaces in the beginnin or end of the string (trim)
For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):
s = s.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ');
The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.
var x = " Test Test Test ".split(" ").join("");
alert(x);
Try this.
var string = " string 1";
string = string.trim().replace(/\s+/g, ' ');
the result will be
string 1
What happened here is that it will trim the outside spaces first using trim() then trim the inside spaces using .replace(/\s+/g, ' ').
How about this one?
"my test string \t\t with crazy stuff is cool ".replace(/\s{2,9999}|\t/g, ' ')
outputs "my test string with crazy stuff is cool "
This one gets rid of any tabs as well
If you want to restrict user to give blank space in the name just create a if statement and give the condition. like I did:
$j('#fragment_key').bind({
keypress: function(e){
var key = e.keyCode;
var character = String.fromCharCode(key);
if(character.match( /[' ']/)) {
alert("Blank space is not allowed in the Name");
return false;
}
}
});
create a JQuery function .
this is key press event.
Initialize a variable.
Give condition to match the character
show a alert message for your matched condition.

Categories