Replace whitespace whitespace and put string a new array - javascript

I would like to remove all whitespace and special char and put ever nummer in a new array like this: var numbers = ['17','9','18','4A'];
This what i am doing to remove whitespace and special character, but how do put clean it more and put in a array?
var str = "(17 - 9), (18 - 4A)"
str.replace(/[()-\s]/g, '');
output: "179,184A"

Don't think of it as removing the extra stuff and just think of it as grabbing what you want.
var input = "(17 - 9), (18 - 4A)";
// Match anything which has one or more numbers or letters in a row
var pattern = /[\da-z]+/gi;
var output = input.match(pattern);
console.log(output);

You can use split method, it returns an array:
var myArray = str.replace(/[()-\s]/g, '').split(',');

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);

Get all characters except hyphen and brackets from string using javascript regex

I have a string like this:
var myString = "MyString-[ADDAAD]-isGreat";
I want to extract this string into 3 parts:
var stringOne = "MyString-";
var stringTwo = "ADDAAD";
var stringThree = "-isGreat";
I know how to get the string between the two square brackets:
var matches = patternString.match(/\[(.*?)\]/);
now matches[1] contains ADDAAD
But how can I get the other two parts?
Select every character except -, [ and ] using bottom regex.
var myString = "MyString-[ADDAAD]-isGreat";
var parts = myString.match(/[^-\[\]]+/g);
console.log(parts);
So if you want to store values in custom variable, use bottom code
var stringOne = parts[0];
var stringTwo = parts[1];
var stringThree = parts[2];
You may split the string with your regex. Note that all the capturing group contents will be also part of the resulting array. To avoid empty items, you may add .filter(Boolean) after split().
See a JS demo below:
var myString = "MyString-[ADDAAD]-isGreat";
console.log(myString.split(/\[(.*?)]/).filter(Boolean));
console.log("s1-[s2]".split(/\[(.*?)]/).filter(Boolean));
Note you do not have to escape a ] used outside character classes, it is always parsed as a literal closing bracket if there is no corresponding [ before it.

How do I split a string with multiple commas and colons in javascript? [duplicate]

This question already has answers here:
How do I split a string with multiple separators in JavaScript?
(25 answers)
Closed 8 years ago.
How do I split a string with multiple separators in JavaScript? I'm trying to split on both commas and : colon but, js's split function only supports one separator.
Example :
materialA:125,materialB:150,materialC:175
I want to split both these values into array like
materiaA,materialB,materialC
and second
125,150,175
Or anybody can give me idea how could I multiply these numbers with a constant to get like
materialA:1250, materialB:1500,materialC:1750.
You can split with more than one seperator if you're using regex:
.split(/:|,/)
This would give
["materialA", "125", "materialB", "150", "materialC", "175"]
Changing the approach completely, if all you want to do is multiply all the numbers in your string by a fixed coefficient, you can use string.replace:
var string = "materialA:125,materialB:150,materialC:175";
var coef = 10;
var result = string.replace(/\d+/g, function(match){
return parseInt(match)*coef;
});
Then print(result) outputs the string
materialA:1250,materialB:1500,materialC:1750
\d is a shortcut for [0-9].
Example using #mitim's method:
var str = 'materialA:125,materialB:150,materialC:175',
multiplier = 2;
str = str.split(',').map(function (elem) {
var parts = elem.split(':');
parts[1] *= multiplier;
return parts.join(':');
}).join(',');
This will give you:
materialA:250,materialB:300,materialC:350
You could split the string by comma first, then loop through the resulting array. In that array, each entry would be something like "materialA:125". From there, you can split by the colon and append each part to its own list to work with or if you prefer, just multiply the second half (cast to int first) and rejoin it in to your original string.
Even though someone gave a much better answer, here's a bit of code that does what I mentioned above (since you asked)
var inputString = "materialA:125,materialB:150,materialC:175";
var mats = new Array();
var numbers = new Array();
var temp;
var elements = inputString.split(",");
for(var element in elements){
temp = elements[element].split(":");
mats.push(temp[0]);
numbers.push(parseInt(temp[1]));
}
console.log(mats); // prints ["materialA", "materialB", "materialC"]
console.log(numbers); // prints [125, 150, 175]
You could simply use following Regex:
/[:,]/
And following string method:
mystring = 'materialA:125,materialB:150,materialC:175';
result = mystring.split(/[:,]/);
Here is a Fiddle.

How to remove the last matched regex pattern in javascript

I have a text which goes like this...
var string = '~a=123~b=234~c=345~b=456'
I need to extract the string such that it splits into
['~a=123~b=234~c=345','']
That is, I need to split the string with /b=.*/ pattern but it should match the last found pattern. How to achieve this using RegEx?
Note: The numbers present after the equal is randomly generated.
Edit:
The above one was just an example. I did not make the question clear I guess.
Generalized String being...
<word1>=<random_alphanumeric_word>~<word2>=<random_alphanumeric_word>..~..~..<word2>=<random_alphanumeric_word>
All have random length and all wordi are alphabets, the whole string length is not fixed. the only text known would be <word2>. Hence I needed RegEx for it and pattern being /<word2>=.*/
This doesn't sound like a job for regexen considering that you want to extract a specific piece. Instead, you can just use lastIndexOf to split the string in two:
var lio = str.lastIndexOf('b=');
var arr = [];
var arr[0] = str.substr(0, lio);
var arr[1] = str.substr(lio);
http://jsfiddle.net/NJn6j/
I don't think I'd personally use a regex for this type of problem, but you can extract the last option pair with a regex like this:
var str = '~a=123~b=234~c=345~b=456';
var matches = str.match(/^(.*)~([^=]+=[^=]+)$/);
// matches[1] = "~a=123~b=234~c=345"
// matches[2] = "b=456"
Demo: http://jsfiddle.net/jfriend00/SGMRC/
Assuming the format is (~, alphanumeric name, =, and numbers) repeated arbitrary number of times. The most important assumption here is that ~ appear once for each name-value pair, and it doesn't appear in the name.
You can remove the last token by a simple replacement:
str.replace(/(.*)~.*/, '$1')
This works by using the greedy property of * to force it to match the last ~ in the input.
This can also be achieved with lastIndexOf, since you only need to know the index of the last ~:
str.substring(0, (str.lastIndexOf('~') + 1 || str.length() + 1) - 1)
(Well, I don't know if the code above is good JS or not... I would rather write in a few lines. The above is just for showing one-liner solution).
A RegExp that will give a result that you may could use is:
string.match(/[a-z]*?=(.*?((?=~)|$))/gi);
// ["a=123", "b=234", "c=345", "b=456"]
But in your case the simplest solution is to split the string before extract the content:
var results = string.split('~'); // ["", "a=123", "b=234", "c=345", "b=456"]
Now will be easy to extract the key and result to add to an object:
var myObj = {};
results.forEach(function (item) {
if(item) {
var r = item.split('=');
if (!myObj[r[0]]) {
myObj[r[0]] = [r[1]];
} else {
myObj[r[0]].push(r[1]);
}
}
});
console.log(myObj);
Object:
a: ["123"]
b: ["234", "456"]
c: ["345"]
(?=.*(~b=[^~]*))\1
will get it done in one match, but if there are duplicate entries it will go to the first. Performance also isn't great and if you string.replace it will destroy all duplicates. It would pass your example, but against '~a=123~b=234~c=345~b=234' it would go to the first 'b=234'.
.*(~b=[^~]*)
will run a lot faster, but it requires another step because the match comes out in a group:
var re = /.*(~b=[^~]*)/.exec(string);
var result = re[1]; //~b=234
var array = string.split(re[1]);
This method will also have the with exact duplicates. Another option is:
var regex = /.*(~b=[^~]*)/g;
var re = regex.exec(string);
var result = re[1];
// if you want an array from either side of the string:
var array = [string.slice(0, regex.lastIndex - re[1].length - 1), string.slice(regex.lastIndex, string.length)];
This actually finds the exact location of the last match and removes it regex.lastIndex - re[1].length - 1 is my guess for the index to remove the ellipsis from the leading side, but I didn't test it so it might be off by 1.

How can I remove all characters up to and including the 3rd slash in a string?

I'm having trouble with removing all characters up to and including the 3 third slash in JavaScript. This is my string:
http://blablab/test
The result should be:
test
Does anybody know the correct solution?
To get the last item in a path, you can split the string on / and then pop():
var url = "http://blablab/test";
alert(url.split("/").pop());
//-> "test"
To specify an individual part of a path, split on / and use bracket notation to access the item:
var url = "http://blablab/test/page.php";
alert(url.split("/")[3]);
//-> "test"
Or, if you want everything after the third slash, split(), slice() and join():
var url = "http://blablab/test/page.php";
alert(url.split("/").slice(3).join("/"));
//-> "test/page.php"
var string = 'http://blablab/test'
string = string.replace(/[\s\S]*\//,'').replace(/[\s\S]*\//,'').replace(/[\s\S]*\//,'')
alert(string)
This is a regular expression. I will explain below
The regex is /[\s\S]*\//
/ is the start of the regex
Where [\s\S] means whitespace or non whitespace (anything), not to be confused with . which does not match line breaks (. is the same as [^\r\n]).
* means that we match anywhere from zero to unlimited number of [\s\S]
\/ Means match a slash character
The last / is the end of the regex
var str = "http://blablab/test";
var index = 0;
for(var i = 0; i < 3; i++){
index = str.indexOf("/",index)+1;
}
str = str.substr(index);
To make it a one liner you could make the following:
str = str.substr(str.indexOf("/",str.indexOf("/",str.indexOf("/")+1)+1)+1);
You can use split to split the string in parts and use slice to return all parts after the third slice.
var str = "http://blablab/test",
arr = str.split("/");
arr = arr.slice(3);
console.log(arr.join("/")); // "test"
// A longer string:
var str = "http://blablab/test/test"; // "test/test";
You could use a regular expression like this one:
'http://blablab/test'.match(/^(?:[^/]*\/){3}(.*)$/);
// -> ['http://blablab/test', 'test]
A string’s match method gives you either an array (of the whole match, in this case the whole input, and of any capture groups (and we want the first capture group)), or null. So, for general use you need to pull out the 1th element of the array, or null if a match wasn’t found:
var input = 'http://blablab/test',
re = /^(?:[^/]*\/){3}(.*)$/,
match = input.match(re),
result = match && match[1]; // With this input, result contains "test"
let str = "http://blablab/test";
let data = new URL(str).pathname.split("/").pop();
console.log(data);

Categories

Resources