Matching string between first and last quote - javascript

I have a string that contains a JSON object. Problem is the object is being returned like this for some reason:
string (4345) "{ "blabla" : { "bleble" : "bloblo" } ...}"
I need to extract everything between the first and last quotation basicly so that I can then decode the object.
I tried this in javascript:
var myVar = myString.match(/\".+$\"/);
But it's not working. What's the appropriate RegEx for my problem?

So you know that (in your example) myString has your JSONed thing? Why not do:
var myVar = myString.substring(1, myString.length - 2);
If there's some other junk before or after your JSONed thing, I guess you could use the indexOf and lastIndexOf operations.
Also check out this question:
Regex to validate JSON
In response to the question in the comment:
//So let's say we have this string
example = '"[ { "title": "event1", "start": "NOW", } ]"'
//So our example string has quote literals around the bits we want
//indexOf gives us the index of the " itself, so we should add one
//to get the character immediately after the "
first_nonquote_character = example.indexOf('"') + 1
//lastIndexOf is fine as is, since substring doesn't include the character
//at the ending index
last_nonquote_character = example.lastIndexOf('"')
//So we can use the substring method of the string object and the
//indices we created to get what we want
string_we_want = example.substring(first_nonquote_character, last_nonquote_character)
//The value in string_we_want is
//[ { "title": "event1", "start": "NOW", } ]
Hope that helps. BTW if your JSON is actually coming back with the ', } ]"' at the end of it and that's not a typo, you'd probably want to do a string.replace(/, } ]"$/, '}]').

You just need to get the group submatch:
/"(.*)"/.exec(myString)[1]

This regex worked for me (I tested it with Rubular):
/"(.+)"/
And you could use it like this:
var newString = oldString.replace(/"(.+)"/, "$1");
Where the parens are for capturing what's in between the quotation marks (because you didn't want them, right?).

Try this:
var newstr = oldstr.match(/"(.+)"/)[1];

Related

Capitalize the first letter of each word

var name = "AlbERt EINstEiN";
function nameChanger(oldName) {
var finalName = oldName;
// Your code goes here!
finalName = oldName.toLowerCase();
finalName = finalName.replace(finalName.charAt(0), finalName.charAt(0).toUpperCase());
for(i = 0; i < finalName.length; i++) {
if (finalName.charAt(i) === " ")
finalName.replace(finalName.charAt(i+1), finalName.charAt(i+1).toUpperCase());
}
// Don't delete this line!
return finalName;
};
// Did your code work? The line below will tell you!
console.log(nameChanger(name));
My code as is, returns 'Albert einstein'. I'm wondering where I've gone wrong?
If I add in
console.log(finalName.charAt(i+1));
AFTER the if statement, and comment out the rest, it prints 'e', so it recognizes charAt(i+1) like it should... I just cannot get it to capitalize that first letter of the 2nd word.
There are two problems with your code sample. I'll go through them one-by-one.
Strings are immutable
This doesn't work the way you think it does:
finalName.replace(finalName.charAt(i+1), finalName.charAt(i+1).toUpperCase());
You need to change it to:
finalName = finalName.replace(finalName.charAt(i+1), finalName.charAt(i+1).toUpperCase());
In JavaScript, strings are immutable. This means that once a string is created, it can't be changed. That might sound strange since in your code, it seems like you are changing the string finalName throughout the loop with methods like replace().
But in reality, you aren't actually changing it! The replace() function takes an input string, does the replacement, and produces a new output string, since it isn't actually allowed to change the input string (immutability). So, tl;dr, if you don't capture the output of replace() by assigning it to a variable, the replaced string is lost.
Incidentally, it's okay to assign it back to the original variable name, which is why you can do finalName = finalName.replace(...).
Replace is greedy
The other problem you'll run into is when you use replace(), you'll be replacing all of the matching characters in the string, not just the ones at the position you are examining. This is because replace() is greedy - if you tell it to replace 'e' with 'E', it'll replace all of them!
What you need to do, essentially, is:
Find a space character (you've already done this)
Grab all of the string up to and including the space; this "side" of the string is good.
Convert the very next letter to uppercase, but only that letter.
Grab the rest of the string, past the letter you converted.
Put all three pieces together (beginning of string, capitalized letter, end of string).
The slice() method will do what you want:
if (finalName.charAt(i) === " ") {
// Get ONLY the letter after the space
var startLetter = finalName.slice(i+1, i+2);
// Concatenate the string up to the letter + the letter uppercased + the rest of the string
finalName = finalName.slice(0, i+1) + startLetter.toUpperCase() + finalName.slice(i+2);
}
Another option is regular expression (regex), which the other answers mentioned. This is probably a better option, since it's a lot cleaner. But, if you're learning programming for the first time, it's easier to understand this manual string work by writing the raw loops. Later you can mess with the efficient way to do it.
Working jsfiddle: http://jsfiddle.net/9dLw1Lfx/
Further reading:
Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
slice() method
You can simplify this down a lot if you pass a RegExp /pattern/flags and a function into str.replace instead of using substrings
function nameChanger(oldName) {
var lowerCase = oldName.toLowerCase(),
titleCase = lowerCase.replace(/\b./g, function ($0) {return $0.toUpperCase()});
return titleCase;
};
In this example I've applied the change to any character . after a word boundary \b, but you may want the more specific /(^| )./g
Another good answer to this question is to use RegEx to do this for you.
var re = /(\b[a-z](?!\s))/g;
var s = "fort collins, croton-on-hudson, harper's ferry, coeur d'alene, o'fallon";
s = s.replace(re, function(x){return x.toUpperCase();});
console.log(s); // "Fort Collins, Croton-On-Hudson, Harper's Ferry, Coeur D'Alene, O'Fallon"
The regular expression being used may need to be changed up slightly, but this should give you an idea of what you can do with regular expressions
Capitalize Letters with JavaScript
The problem is twofold:
1) You need to return a value for finalName.replace, as the method returns an element but doesn't alter the one on which it's predicated.
2) You're not iterating through the string values, so you're only changing the first word. Don't you want to change every word so it's in lower case capitalized?
This code would serve you better:
var name = "AlbERt EINstEiN";
function nameChanger(oldName) {
// Your code goes here!
var finalName = [];
oldName.toLowerCase().split(" ").forEach(function(word) {
newWord = word.replace(word.charAt(0), word.charAt(0).toUpperCase());
finalName.push(newWord);
});
// Don't delete this line!
return finalName.join(" ");
};
// Did your code work? The line below will tell you!
console.log(nameChanger(name));
if (finalName.charAt(i) === " ")
Shouldn't it be
if (finalName.charAt(i) == " ")
Doesn't === check if the object types are equal which should not be since one it a char and the other a string.

Check if next character of a match, matches

in order to explain myself better.
I have the following string
var a = 'Dg_DQ_DA'
And i pass for example DQ
I want to check if string a contains DQ, that i can do, but also i want to check DQ next character, or know what character is only if it matches, i'm kinda stuck on how to do that dumb thing.
Thanks.
As pointed out by soktinpk, you can concatenate the "needle" string with "_", and use indexOf as usual:
haystack.indexOf(needle + "_") != -1
Try this.
var str = 'Dg_DQ_DA';
//check if string a contains DQ
if(/DQ/g.test(str)){
var nst = str.match(/DQ./g);
console.log(nst[0].slice(-1)); //To get the last character
}else{
//Not Found
}
The result of console will be:
_

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)

How can I get a substring located between 2 quotes?

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.

Remove part an ever-changing text string with javascript?

I have a string of text "AB-123-2011-07-09", and need to remove everything except "123", then add a "#" sign to the end result.
The string "123" is ever increasing in number, as is the "2011-07-09" (a date). Only "AB" stays the same.
So the end result would be: #123
Is this possible?
Thanks.
EDIT: Just to clarify, I was needing a script that could globally search a page and replace any text which had the format of "AB-xxx-xxxx-xx-xx" with just the digits highlighted here in bold, then adding the "#" before it.
Currently there are only 3 digits in that position, but in the future there may be four.
My code:
function Replace() {
var OldString = "AB-123-2011-07-09";
var NewString = OldString.replace(/^AB-(\d+)-.*/, "#$1");
document.body.innerHTML = document.body.innerHTML.replace(OldString, NewString);
}
window.onload = Replace();
So far it only replaces 1 instance of the string, and uses a fixed string ("AB-123-2011-07-09").
What regular expression do I need to make the 'OldString' dynamic, rather than it being fixed as it is now?
var data = "AB-123-2011-07-09";
var field = data.split('-')[1];
document.write("#" + field);
http://jsfiddle.net/efortis/8acDr/
The following regex would work, but in this case I don't think you need a regex at all (as #Eric has already shown).
"AB-123-2011-07-09".replace(/^AB-(\d+)-.*/, "#$1");
This results in the value #123
http://jsfiddle.net/3XhbE/
Does this work?
var result = mystring.replace(new RegExp(AB-([0-9]+)-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9], "g"),"#$1");
mystring is the "AB-123-2011-07-09" string and result would be "#123".
This is of course possible. This regex would do the trick:
“AB-123-2011-07-09“.replace(/^AB-(\d+)-\d+-\d+-\d+$/, “#$1“);
It also checks you given syntax and that there is nothing else in the string.
migg

Categories