How to get a specific part of a string in Javascript? - javascript

I have a string:
string = 'XXXXXXXXXXXXtext:hello,XXXXXXX'
I want to retrieve hello. XXXXXXXX is some random text. The only thing I know is that hello is between text: and ,.

You can use a regular expression to retrieve the text you need. Try this:
var str = 'XXXXXXXXXXXXtext:hello,XXXXXXX';
var matches = /text\:(.+),/gi.exec(str);
console.log(matches[1]);
If there are multiple instances of text: within your string then you can use a loop to iterate through the result of exec() and retrieve them all.

Related

javascript split string function not working

I am trying to split a string:
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
var res = device_data.split('*');
But it's not working. it's just displaying this string
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
var res = str.split('*');
console.dir(res)
,HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#,HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555
Instead of creating an array with two elements.
IMHO, you want something like this:
var str = "*HQ,6170930129,V1,185409,A,3132.3228,N,07424.7726,E,000.04,000,280618,FBFFBBFF,410,04,08028,40555#*HQ,6170930129,V1,185413,A,3132.3226,N,07424.7735,E,000.15,000,280618,FBFFBBFF,410,04,08028,40555"
splitStrArr = str.split('*').filter(str => str != "")
console.log(splitStrArr)
console.log(splitStrArr[0])
console.log(splitStrArr[1])
You are getting a string with a period in the beginning because whatever you are doing leads to the result of String#split being converted to a string. String#split returns an array. An array converted to a string is of the form of element0,element1,element2 ... elements separated by commas.
The result of String#split in your case is ["",...] with 3 elements since your string begins with the character '*' you are searching, so String#split will create an empty string as the first element of the returned array. So the result is exactly as expected, and String#split is working as intended.
get rid of the first character of the string,
mystring.substr(1).split('*')
get rid of the empty strings
mystring.split('*').filter(s=>s!='')
to obtain the desired result.
You can use:
var res = str.split("#");
You can check in Javascript console in browser itself.
As a suggestion/ idea, you can always use the browser console, for example, Chrome browser, to execute simple scripts like these.
This way, you can save time, as it is easier to check your data structures, their internal data.
If you try
var res = str.split('*');
you obtain three elements:
res[0] is '' (empty string)
res[1] is 'HQ,61...'
res[2] is 'HQ,...'

JavaScript regular Expression to extract a substring which is in double qoutes, from a master string

i have a string , which look like an array of strings. I need a regex pattern in javascript to extract the substrings inside that master string, and return me the substring. Look at the string given below, and i need a regex on the basis of this string. And the regex will extract the substrings like :
files/file/img1.jpg ,files/file/img2.jpg and so on, until the end. As much directories i have , i want them to be extracted. For time being just consider that its not an array, its just a string. Thank you
str =
"["files/file/img1.jpg","files/file/img2.jpg","files/file/img3.jpg","files/file/img4.jpg","files/file/img5.jpg","files/file/img6.jpg"] ";
Use JSON.parse to parse your string.Then just iterate over the array.
var str =
'["files/file/img1.jpg","files/file/img2.jpg","files/file/img3.jpg","files/file/img4.jpg","files/file/img5.jpg","files/file/img6.jpg"]';
var result = JSON.parse(str);
for(var i= 0; i< result.length;i++){
console.log(result[i]);
}
The syntax is kinda wrong. It should be:
var str ="[\"files/file/img1.jpg\",\"files/file/img2.jpg\",\"files/file/img3.jpg\",\"files/file/img4.jpg\",\"files/file/img5.jpg\",\"files/file/img6.jpg\"] ";
Apart from that we can just use multiple Javascript string manipulation functions to extract the string:
data = str.split('["')[1].split('"]')[0].replace(/"/g, "").split(',');
Now the variable data is an array which has all the directories you need. The output looks something like this:
(6) ["files/file/img1.jpg", "files/file/img2.jpg", "files/file/img3.jpg", "files/file/img4.jpg", "files/file/img5.jpg", "files/file/img6.jpg"]
You can get each directory by indexing it: data[0] is the first one.

Extract Twitter handlers from string using regex in JavaScript

I Would like to extract the Twitter handler names from a text string, using a regex. I believe I am almost there, except for the ">" that I am including in my output. How can I change my regex to be better, and drop the ">" from my output?
Here is an example of a text string value:
"PlaymakersZA, Absa, DiepslootMTB"
The desired output would be an array consisting of the following:
PlaymakersZA, Absa, DiepslootMTB
Here is an example of my regex:
var array = str.match(/>[a-z-_]+/ig)
Thank you!
You can use match groups in your regex to indicate the part you wish to extract.
I set up this JSFiddle to demonstrate.
Basically, you surround the part of the regex that you want to extract in parenthesis: />([a-z-_]+)/ig, save it as an object, and execute .exec() as long as there are still values. Using index 1 from the resulting array, you can find the first match group's result. Index 0 is the whole regex, and next indices would be subsequent match groups, if available.
var str = "PlaymakersZA, Absa, DiepslootMTB";
var regex = />([a-z-_]+)/ig
var array = regex.exec(str);
while (array != null) {
alert(array[1]);
array = regex.exec(str);
}
You could just strip all the HTML
var str = "PlaymakersZA, Absa, DiepslootMTB";
$handlers = str.replace(/<[^>]*>|\s/g,'').split(",");

Javascript Value Replace for Multiple Values

I am trying to replace multiple values in a string with JS replace(). The values that I want to replace include line breaks, &, #, etc... I know how to replace one value:
var string = document.getElementById('string').value.replace(\/n/g, '<br>');
However, what is the syntax to include other values. For example, how can I make the below replace functions one function?
var string = document.getElementById('string').value.replace(\/n/g, '<br>')
var string = document.getElementById('string').value.replace('&', '%26');
You could chain it simply.
var string = document.getElementById('string').value.replace(/\n/g, '<br>').replace('&', '%26');

Regular expressions for parsing "real" words in JavaScript

I've got some text where some words are "real" words, and others are masks that will be replaced with some text and that are surrounded with, say, "%". Here's the example:
Hello dear %Name%! You're %Age% y.o.
What regular expression should I use to get "real" words, without using lookbehind, because they don't exist in JavaScript?
UPD: I want to get words "Hello", "dear", "you're", "y.o.".
If I've understood your question correctly this might work.
I would go about it the other way around, instead of finding the real words I would remove the "fake-words."
s = "Hello dear %Name%! You're %Age% y.o."
realWords = s.replace(/%.*?%/g, "").split(/ +/)
You could use split to get the words and filter the words afterwards:
var str = "Hello dear %Name%! You're %Age% y.o.", words;
words = str.split(/\s+/).filter(function(val) {
return !/%[^%]*%/.test(val);
});
To do a search and replace with regexes, use the string's replace() method:
myString.replace(/replaceme/g, "replacement")
Using the /g modifier makes sure that all occurrences of "replaceme" are replaced. The second parameter is an normal string with the replacement text.
You can match the %Something% matches using %[^%]*?%, but how are you storing all of the individual mask values like Name and Age?
Use regular expression in Javascript and split the string based on matching regular expression.
//javascript
var s = "Hello dear %Name%! You're %Age% y.o.";
words = s.split(/%[^%]*?%/i);
//To get all the words
for (var i = 0; i < words.length; i++) {
}

Categories

Resources