how to get numbers from a string in javascript? - javascript

I have
"id": 1468306
inside of a string, how can I use regular expression to get the number 1468306 for it?

You can use this regex:
/: (\d+)/
as in:
s = '"id": 1468306';
r = /: (\d+)/;
console.log(r.exec(s)[1]);
Output:
1468306

you can use parseInt() method in javascript as follows:
var str = parseInt(id);

Following code may help you:
var input = '"id": 1468306';
var matches = input.match(/"id": (\d+)/);
var id = matches[1];
The id get the required number.

JSON.parse("{" + yourString + "}").id
Will be your number if you have that in a String.

Fiddle: http://jsfiddle.net/SfeMh/
var regEx = /\d+/g;
var str = '"id": 1468306';
var numbers = str.match(regEx);
alert(numbers); // returns 1468306
It looks like you're trying to parse a JSON String. Try this way as already mentioned:
var parsedObj = JSON.parse(myJSONString);
alert(parsedObj.id); // returns 1468306

This will match in this cases
id : 156454;
id :156454;
id:156454;
/id\s?[:]\s?[0-9]+/g.match(stringhere)

Alright, my JSON answer still stands, use it if that's your full string you're giving us in the question. But if you really want a regex, here's one that will search for "id" and then find the number after.
parseInt(yourString.match(/("id"\s?:\s?)(\d+)/)[2])
Fiddle: http://jsfiddle.net/tS9M4/

Related

How to get the string just before specific character in JavaScript?

I have couple of strings like this:
Mar18L7
Oct13H0L7
I need to grab the string like:
Mar18
Oct13H0
Could any one please help on this using JavaScript? How can I split the string at the particular character?
Many Thanks in advance.
For var str = 'Mar18L7';
Try any of these:
str.substr(0, str.indexOf('L7'));
str.split('L7')[0]
str.slice(0, str.indexOf('L7'))
str.replace('L7', '')
Based on input that is given it I have created following function which can take n string in array and return the output in the format you have given. Check if this helps and if some use case is missed.
function generateStr(arr, splitStr) {
const processedStr = arr.map(value => value.split(splitStr)[0]);
return processedStr.join(" OR ");
}
console.log(generateStr(["Mar18L7", "Oct13H0L7"], "L7"));
You can use a regex like this
var data = ["Mar18L7", "Oct13H0L7"];
var regex = /^([a-zA-Z0-9]+)\L[a-zA-Z0-9]+$/;
var output = []
data.forEach(function(el){
var matches = el.match(regex);
output.push(matches[1]);
});
output variable will be equal to ['Mar18', 'Oct13H0'] and you can join all value usin the .join method on output array
var chain = output.join(" OR ");
// chain will be equal to "Mar18 OR Oct13H0"

Replace in javascript

I have a string something like this:
http://stackoverflow.com/questions/ask
And would like to return this part:
http://stackoverflow.com/questions/
How can I do this using pure javascript?
Thanks!
This will match and remove the last part of a string after the slash.
url = "http://stackoverflow.com/questions/ask"
base = url.replace(/[^/]*$/, "")
document.write(base)
Help from: http://www.regexr.com/
For slicing off last part:
var test = 'http://stackoverflow.com/questions/ask';
var last = test.lastIndexOf('/');
var result = test.substr(0, last+1);
document.write(result);
You can accomplish this with the .replace() method on String objects.
For example:
//Regex way
var x = "http://stackoverflow.com/questions/ask";
x = x.replace(/ask/, "");
//String way
x = x.replace('ask', "");
//x is now equal to the string "http://stackoverflow.com/questions/"
The replace method takes two parameters. The first is what to replace, which can either be a string or regex, literal or variable, and the second parameter is what to replace it with.

Regex to replace a string containing variable

I'm new to regex. I got a prob here. I work with xpaths strings. I want to remove a particular element from xpath string if the element has id = myVar
Example:
/html/body/div[3]/div[20]/section[1]/p[5]/span[1][#id="var645932"]/span
I want to replace the /span[1][#id="var645932"]/ with just / if my variable value is equal to id value i.e var645932
I need to do it in javascript. all are strings. I prefer regex. if any regex experts are there Kindly help. am stuck here. is it possible to accomplish it without regex ??
Any help are highly appreciated :) TIA
Try this:
var input = '/html/body/div[3]/div[20]/section[1]/p[5]/span[1][#id="var645932"]/span';
var regex = /\w+\[\w+\]\[\#id="var645932"\]\//gi;
input = input.replace(regex, '');
console.log(input);
Example fiddle
This regex is designed to work even if the structure of the HTML changes, eg:
var input = '/html/body/div[3]/div[20]/section[1]/div[6][#id="var645932"]/span';
If you need to set the id in the regex programmatically, use this:
var regex = new RegExp('/\w+\[\w+\]\[\#id="' + id + '"\]\//', 'gi');
You can use below code -
var expr = '/html/body/div[3]/div[20]/section[1]/p[5]/span[1][#id="var645932"]/span';
var idVal = "var645932";
expr = expr.replace('span[1][#id="'+idVal+'"]/','');
DEMO
Well, you could do it in the following way
var id = "var645932";
var regx = new RegExp('/[^/]+?\\[#id="' + id + '"]/');
var str = '/html/body/div[3]/div[20]/section[1]/p[5]/span[1][#id="var645932"]/span';
console.log(str.replace(regx, "/"));

How to use split in javascript

I have a string like
/abc/def/hij/lmn.o // just a raw string for example dont know what would be the content
I want only /abc/def/hij part of string how do I do that.
I tried using .split() but did not get any solution.
If you want to remove the particular string /lmn.o, you can use replace function, like this
console.log(data.replace("/lmn.o", ""));
# /abc/def/hij
If you want to remove the last part after the /, you can do this
console.log("/" + data.split("/").slice(1, -1).join("/"));
# /abc/def/hij
you can do
var str = "/abc/def/hij/lmn.o";
var dirname = str.replace(/\/[^/]+$/, "");
Alternatively:
var dirname = str.split("/").slice(0, -1).join("/");
See the benchmarks
Using javascript
var x = '/abc/def/hij/lmn.o';
var y = x.substring(0,x.lastIndexOf("/"));
console.log(y);
var s= "/abc/def/hij/lmn.o"
var arr= s.split("/");
after this, use
arr.pop();
to remove the last content of the array which would be lmn.o, after which you can use
var new_s= arr.join("/");
to get /abc/def/hij

How do I split this string with JavaScript?

Javascript:
var string = '(37.961523, -79.40918)';
//remove brackets: replace or regex? + remove whitespaces
array = string.split(',');
var split_1 = array[0];
var split_2 = array[1];
Output:
var split_1 = '37.961523';
var split_2 = '-79.40918';
Should I just use string.replace('(', '').replace(')', '').replace(/\s/g, ''); or RegEx?
Use
string.slice(1, -1).split(", ");
You can use a regex to extract both numbers at once.
var string = '(37.961523, -79.40918)';
var matches = string.match(/-?\d*\.\d*/g);
You would probably like to use regular expressions in a case like this:
str.match(/-?\d+(\.\d+)?/g); // [ '37.961523', '-79.40918' ]
EDIT Fixed to address issue pointed out in comment below
Here is another approach:
If the () were [] you would have valid JSON. So what you could do is either change the code that is generating the coordinates to produce [] instead of (), or replace them with:
str = str.replace('(', '[').replace(')', ']')
Then you can use JSON.parse (also available as external library) to create an array containing these coordinates, already parsed as numbers:
var coordinates = JSON.parse(str);

Categories