capture the string next to known string using javascript/jQuery - javascript

I have a long string. How can I find a string next to the known string.
example: '.lot of text..."number":"999.999.9999","make_model":"device name"....lot of text.'.
I know this value "999.999.9999". Using this as a sub string how do I capture "device name" and pass it as an alert/console.log? The device name is not a constant length.
Thanks

you can do something like this if you are sure the number is only repeated once and length is always the same and make_model is always next to it.
basically it finds index of number and adds the length of number plus make_model ("999.999.9999","make_model":") which is 29 characters. and then we get the rest of string after this until we reach a double quotation and thats the end of make_model and what you want.
var str = '.lot of text..."number":"999.999.9999","make_model":"device name"....lot of text.';
var chop = str.substr(str.indexOf('"999.999.9999"') + 29);
chop = chop.substring(0,chop.indexOf('"'));
console.log(chop);

A very straight forward answer is using JSON.parse()
/* surround string with braces { <your string> } */
var input_str = '{' + '"foo":"bar","number":"999.999.9999","make_model":"some model name","device name":"some dummy device","name":"Arvind","profile":"freelancer"' + '}';
var json = JSON.parse(input_str);
console.log(json['device name']);

Related

JavaScript get first name and last name from string as array

I have a string that has the following format: <strong>FirstName LastName</strong>
How can I change this into an array with the first element firstName and second lastName?
I did this, but no luck, it won't produce the right result:
var data = [myString.split('<strong>')[1], myString.split('<strong>')[2]]
How can I produce ["firstName", "lastName"] for any string with that format?
In order to parse HTML, use the best HTML parser out there, the DOM itself!
// create a random element, it doesn't have to be 'strong' (e.g., it could be 'div')
var parser = document.createElement('strong');
// set the innerHTML to your string
parser.innerHTML = "<strong>FirstName LastName</strong>";
// get the text inside the element ("FirstName LastName")
var fullName = parser.textContent;
// split it into an array, separated by the space in between FirstName and LastName
var data = fullName.split(" ");
// voila!
console.log(data);
EDIT
As #RobG pointed out, you could also explicitly use a DOM parser rather than that of an element:
var parser = new DOMParser();
var doc = parser.parseFromString("<strong>FirstName LastName</strong>", "text/html");
console.log(doc.body.textContent.split(" "));
However, both methods work perfectly fine; it all comes down to preference.
Just match everything between <strong> and </strong>.
var matches = "<strong>FirstName LastName</strong>".match(/<strong>(.*)<\/strong>/);
console.log(matches[1].split(' '));
The preferred approach would be to use DOM methods; create an element and get the .textContent then match one or more word characters or split space character.
let str = '<strong>FirstName LastName</strong>';
let [,first, last] = str.split(/<[/\w\s-]+>|\s/g);
console.log(first, last);
/<[/\w\s-]+>|\s/g
Splits < followed by one or more word, space or dash characters characters followed by > character or space to match space between words in the string.
Comma operator , within destructuring assignment is used to omit that index from the result of .split() ["", "FirstName", "LastName", ""].
this is my approach of doing your problem. Hope it helps!
var str = "<strong>FirstName LastName</strong>";
var result = str.slice(0, -9).substr(8).split(" ");
Edit: it will only work for this specific example.
Another way to do this in case you had something other than an html
var string = "<strong>FirstName LastName</strong>";
string = string.slice(0, -9); // remove last 9 chars
string = string.substr(8); // remove first 8 chars
string = string.split(" "); // split into an array at space
console.log(string);

Regex match cookie value and remove hyphens

I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens. I would like to replace the hyphens with a space and set to a variable. Javascript or jQuery.
As an example, the larger string has a name and value like this within it:
facility=34222%7CConner-Department-Store;
(notice the leading "C")
So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex. Then break it down to "Conner Department Store"
var cookie = document.cookie;
var facilityValue = cookie.match( REGEX ); ??
var test = "store=874635%7Csomethingelse;facility=34222%7CConner-Department-Store;store=874635%7Csomethingelse;";
var test2 = test.replace(/^(.*)facility=([^;]+)(.*)$/, function(matchedString, match1, match2, match3){
return decodeURIComponent(match2);
});
console.log( test2 );
console.log( test2.split('|')[1].replace(/[-]/g, ' ') );
If I understood it correctly, you want to make a phrase by getting all the words between hyphens and disallowing two successive Uppercase letters in a word, so I'd prefer using Regex in that case.
This is a Regex solution, that works dynamically with any cookies in the same format and extract the wanted sentence from it:
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Demo:
var str = "facility=34222%7CConner-Department-Store;";
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Explanation:
Use this Regex (/([A-Z][a-z]+)-?/g to match the words between -.
Replace any - occurence in the matched words.
Then just join these matches array with white space.
Ok,
first, you should decode this string as follows:
var str = "facility=34222%7CConner-Department-Store;"
var decoded = decodeURIComponent(str);
// decoded = "facility=34222|Conner-Department-Store;"
Then you have multiple possibilities to split up this string.
The easiest way is to use substring()
var solution1 = decoded.substring(decoded.indexOf('|') + 1, decoded.length)
// solution1 = "Conner-Department-Store;"
solution1 = solution1.replace('-', ' ');
// solution1 = "Conner Department Store;"
As you can see, substring(arg1, arg2) returns the string, starting at index arg1 and ending at index arg2. See Full Documentation here
If you want to cut the last ; just set decoded.length - 1 as arg2 in the snippet above.
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1)
//returns "Conner-Department-Store"
or all above in just one line:
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1).replace('-', ' ')
If you want still to use a regular Expression to retrieve (perhaps more) data out of the string, you could use something similar to this snippet:
var solution2 = "";
var regEx= /([A-Za-z]*)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/;
if (regEx.test(decoded)) {
solution2 = decoded.match(regEx);
/* returns
[0:"facility=34222|Conner-Department-Store",
1:"facility",
2:"34222",
3:"Conner-Department-Store",
index:0,
input:"facility=34222|Conner-Department-Store;"
length:4] */
solution2 = solution2[3].replace('-', ' ');
// "Conner Department Store"
}
I have applied some rules for the regex to work, feel free to modify them according your needs.
facility can be any Word built with alphabetical characters lower and uppercase (no other chars) at any length
= needs to be the char =
34222 can be any number but no other characters
| needs to be the char |
Conner-Department-Store can be any characters except one of the following (reserved delimiters): :/?#[]#;,'
Hope this helps :)
edit: to find only the part
facility=34222%7CConner-Department-Store; just modify the regex to
match facility= instead of ([A-z]*)=:
/(facility)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/
You can use cookies.js, a mini framework from MDN (Mozilla Developer Network).
Simply include the cookies.js file in your application, and write:
docCookies.getItem("Connor Department Store");

Regular expression to test exact word with a trailing dot

I am having a dynamic variable which I need to match against a source.
Source: 'text clientLogin padding float';
search: '.clientLog'
The search text has a leading dot('.') which should be omitted while comparing.
For the above example I should:
Get the part of search after '.'(dot)
Check the source for the search text i.e clientLog & return true if whole word matches.(in this example it should return false as source has clientLogin).
I am trying to use RegEx to achieve this
var regEx = new RegExp(k); // k is the search text
if(regEx.test(classNames)){....
Above code is inside jQuery.each,k is the key of the object which is being iterated.I did not figure out how to omit the '.' but read somewhere to implement Word Boundries for the exact match.
Please suggest.
thanks
Try this:
var
source = 'text clientLogin padding float',
search = '.clientLog',
pattern = '\\b'+search.replace(/^\./, '')+'\\b',
result = new RegExp(pattern).test(source);
Notes:
We strip off the leading '.' from the search string while building the pattern
We use word boundary markers (\b). This helps ensure that "login" is not considered a valid match for "log", for example, like in your case.
The double-escaping (\\b) is necessary as we're building our pattern as a string - this is necessary for dynamic patterns fed to the RegExp constructor.
Stripping text
In JavaScript, you can strip text with the substring() method like this:
var str = "Hello World!";
var sub_str = str.substring(1, str.length);
In substring(x, y), x is the starting index of the new string, y is the ending index. The indecies in JavaScript start at 0, so we have to use the next index to omit the first character in the string.
You can also read it up here on W3Schools.
Regular Expressions
You can search RegEx patterns in strings like this:
var str = "Hello World!";
var pos = str.search(/World/); // Attention: No quotes here!
pos equals the index of the first match of the given expression. If your expression did not match your string, then pos will equal -1.
Note, that str.search(/World/); is basicly the same as str.search(new RegExp("World"));
You can also read it up here on W3Schools.
To check, if your string contains that classname, you could do this:
var str = "classname1 classname2 classname3";
var search_str = ".classname2";
if(str.search(new RegExp("\\b(" + search_str.substring(1, search_str.length) + ")\\b")) > -1){
// classname found
} else {
//classname not found
}

How to get the last value of a string?

How can i control in java script, wheter the last character in a string is a ", " and how can i delete the last character, if it is a ", "?
var stringToControl = "ABC, XYZ, OOP, "
"Comma followed by any number of white space characters at the end of a string" can be expressed as a regular expression: /,\s*$/.
So to get rid of it you can replace it with an empty string:
stringToControl = stringToControl.replace(/,\s*$/,'');
Try this:
if (stringToControl.slice(-2) === ', ') {
stringToControl = stringToControl.slice(0, -2);
}
slice method returns part of a string. First argument is the start position and optional second argument - the end position. If you don't pass second arguments, slice will return part from start argument to the end of the string. If you pass negative value, it means the position from the end (so .slice(-2) means 2 last characters).
Here is an article on MDN
Another approach is to use RegExp:
stringToControl = stringToControl.replace(/, $/, '');
use slice
var temp = "abcd,aa,a,as,c,d, ".trim();
if(temp.endsWith(','))
temp = temp.slice(0,-1);
temp

How do I split a string that contains different signs?

I want to split a string that can look like this: word1;word2;word3,word4,word5,word6.word7. etc.
The string is from an output that I get from a php page that collects data from a database so the string may look different but the first words are always separated with ; and then , and the last words with .(dot)
I want to be able to fetch all the words that ends with for example ; , or . into an array. Does someone know how to do this?
I would also like to know how to fetch only the words that ends with ;
The function ends_with(string, character) below works but it takes no regard to whitespace. For example if the word is Jonas Sand, it only prints Sand. Anybody knows how to fix this?
Probably
var string = "word1;word2;word3,word4,word5,word6.word7";
var array = string.split(/[;,.]/);
// array = ["word1", "word2", "word3", "word4", "word5", "word6", "word7"]
The key is in the regular expression passed to the String#split method. The character class operator [] allows the regular expression to select between the characters contained with it.
If you need to split on a string that contains more than one character, you can use the | to differentiate.
var array = string.split(/;|,|./) // same as above
Edit: Didn't thoroughly read the question. Something like this
var string = "word1;word2;word3,word4,word5,word6.word7";
function ends_with(string, character) {
var regexp = new RegExp('\\w+' + character, 'g');
var matches = string.match(regexp);
var replacer = new RegExp(character + '$');
return matches.map(function(ee) {
return ee.replace(replacer, '');
});
}
// ends_with(string, ';') => ["word1", "word2"]
var myString = word1;word2;word3,word4,word5,word6.word7;
var result = myString.split(/;|,|./);

Categories

Resources