Javascript string separated by a comma - javascript

I'm trying to get everything before/after a comma from a string
var test = 'hello,world';
Result:
var one = 'hello';
var two = 'world';
What would be a good way to this?
Thanks

.split
Extra text because I need to write 15 characters for this submission to be approved.
-- edit
okay, more explicitly:
var k = "a,b".split(",");
alert(k[0]);
alert(k[1]);

var test = 'hello,world',
words = test.split(',');
var one = words[0]; // hello
var two = words[1]; // world

Related

I need help getting a number from a <p> element with javascript

I am new in JavaScript. I have 3 numbers with 10 digits in a <p> tag, and I would like to select and convert them to a link. I was able to get the numbers and convert them to link, but I am getting all 3 numbers at the same time as one link, it would be great if I can get some help, Thank you
Here is my code:
<p>
What 0123456789 exactly is this Worker thread module, 9876543210 and why do we need it? 9768352461 In this post, we will talk about the historical reasons concurrency is implemented in JavaScript and Node.js, the problems we might find, current solutions, and the future of parallel processing with Worker threads.
</p>
<script>
function myFunction() {
var str = document.querySelector("p").innerHTML;
var link = 'https://www.google.com/search?q='+text;
var rgx = /\d{10}/g;
var text = str.match(rgx);
var res = str.replace(rgx, '"'+text+'"');
document.querySelector("p").innerHTML = res;
}
myFunction();
</script>
You can capture certain expressions in regex. Then you can get value from that group by using $ and a group number. There's only one group so in this case there'll be $1;
function myFunction() {
var str = document.querySelector("p").innerHTML;
var link = "https://www.google.com/search?q=$1";
var rgx = /(\d{10})/g; // () wraps an expression in a group
var text = str.match(rgx);
var res = str.replace(rgx, '$1');
document.querySelector("p").innerHTML = res;
}
More about capturing groups: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges
Edit: I found even a simpler way - if you want to refer to the whole expression you don't need to create a group. To insert matched value you can use $&:
function myFunction() {
var str = document.querySelector("p").innerHTML;
var link = "https://www.google.com/search?q=$&";
var rgx = /\d{10}/g;
var text = str.match(rgx);
var res = str.replace(rgx, '$&');
document.querySelector("p").innerHTML = res;
}
str.match(rgx);
returns an array of matching strings. If you want to use only on item of the array, you can reference to the index (like text[0]) or you can i.e. loop over the array with text.forEach
or you can map over it and generate links like this:
let links = text.map((string) => { return `www.yourlink.com/${string}`})
in your replace statement use text instead of rgx
var res = str.replace(text, '"'+text+'"');
that way you only replace the instance of the matched text instead of all the rgx matches
EDIT
this should do it
function myFunction() {
var str = document.querySelector("p").innerHTML;
var rgx = /\d{10}/g;
var text = str.match(rgx);
for (i=0; i<text.length; i++) {
var link = 'https://www.google.com/search?q='+text[i];
str = str.replace(text[i], '"'+text[i]+'"');
}
document.querySelector("p").innerHTML = str;
}
myFunction();

Slice from sections from URL

Given these URLs:
/content/etc/en/hotels/couver/offers/residents.html
/content/etc/en/offers/purchase.html
I want to remove (slice) from the URL and get only /offers/residents and /offers/purchase
I wrote this code to do it but I'm getting different results than I require. Please let me know which syntax will work as expected.
var test1 = '/content/etc/en/hotels/couver/offers/residents.html'
test1 = test1.slice(0,5);
var test2 = '/content/etc/en/offers/purchase.html'
test2 = test2.slice(0,5);
One way to achieve this would be to split the strings by / and then only use the last two sections of the path to rebuild a string:
['/content/etc/en/hotels/couver/offers/residents.html', '/content/etc/en/offers/purchase.html'].forEach(function(url) {
var locs = url.replace(/\.\w+$/, '').split('/');
var output = locs.slice(-2).join('/');
console.log(output);
});
Alternatively you could use a regular expression to only retrieve the parts you require:
['/content/etc/en/hotels/couver/offers/residents.html', '/content/etc/en/offers/purchase.html'].forEach(function(url) {
var locs = url.replace(/.+\/(\w+\/\w+)\.\w+$/, '$1');
console.log(locs);
});
You could extract the substring that you want with regex. In the example below the matches[1] will contain the wanted substring.
var str = '/content/etc/en/hotels/couver/offers/residents.html';
var matches = str.match(/([\w]+\/[\w]+)\.html/);
var parsed = matches[1];
this is what you meant for?
to change the slice numbers?
var test1 = '/content/etc/en/hotels/couver/offers/residents.html'
test1 = test1.slice(29,46);
var test2 = '/content/etc/en/offers/purchase.html'
test2 = test2.slice(15,31);
Use regex, to remove everything before and after string, that starts from /offers and ends with .html
const str1 = '/content/etc/en/hotels/couver/offers/residents.html';
const str2 = '/content/etc/en/offers/purchase.html';
const regex = /^(.*)(\/offers\/.*)(.html)$/g;
console.log(str1.replace(regex, '$2')); // /offers/residents
console.log(str2.replace(regex, '$2')); // /offers/purchase
https://regex101.com/r/hRwLHi/1

JavaScript insert text after first parenthesis

everyone. I've got a string looks like
var s = "2qf/tqg4/ad(d=d,s(f)d)"
And I've got another string
var n = "abc = /fd/dsf/sdf/a.doc, "
What I want to do is insert n after the first '('
So it will look like
"2qf/tqg4/ad(abc = /fd/dsf/sdf/a.doc, d=d,s(f)d)"
Just use the replace function:
var result = s.replace("(", "("+n);
This barely needs REs.
var t = s.replace(/\(/, '('+n);
This doesn't need REs at all, as String.replace takes strings as well as REs to specify what should be replaced.
var t = s.replace('(', '('+n);

javascript - get two numbers from a string

I have a string like:
text-345-3535
The numbers can change.
How can I get the two numbers from it and store that into two variables?
var str = "text-345-3535"
var arr = str.split(/-/g).slice(1);
Try it out: http://jsfiddle.net/BZgUt/
This will give you an array with the last two number sets.
If you want them in separate variables add this.
var first = arr[0];
var second = arr[1];
Try it out: http://jsfiddle.net/BZgUt/1/
EDIT:
Just for fun, here's another way.
Try it out: http://jsfiddle.net/BZgUt/2/
var str = "text-345-3535",first,second;
str.replace(/(\d+)-(\d+)$/,function(str,p1,p2) {first = p1;second = p2});
var m = "text-345-3535".match(/.*?-(\d+)-(\d+)/);
m[1] will hold "345" and m[2] will have "3535"
If you're not accustomed to regular expressions, #patrick dw's answer is probably better for you, but this should work as well:
var strSource = "text-123-4567";
var rxNumbers = /\b(\d{3})-(\d{4})\b/
var arrMatches = rxNumbers.exec(strSource);
var strFirstCluster, strSecondCluster;
if (arrMatches) {
strFirstCluster = arrMatches[1];
strSecondCluster = arrMatches[2];
}
This will extract the numbers if it is exactly three digits followed by a dash followed by four digits. The expression can be modified in many ways to retrieve exactly the string you are after.
Try this,
var text = "text-123-4567";
if(text.match(/-([0-9]+)-([0-9]+)/)) {
var x = Text.match(/([0-9]+)-([0-9]+)/);
alert(x[0]);
alert(x[1]);
alert(x[2]);
}
Thanks.
Another way to do this (using String tokenizer).
int idx=0; int tokenCount;
String words[]=new String [500];
String message="text-345-3535";
StringTokenizer st=new StringTokenizer(message,"-");
tokenCount=st.countTokens();
System.out.println("Number of tokens = " + tokenCount);
while (st.hasMoreTokens()) // is there stuff to get?
{words[idx]=st.nextToken(); idx++;}
for (idx=0;idx<tokenCount; idx++)
{System.out.println(words[idx]);}
}
output
words[0] =>text
words[1] => 345
words[2] => 3535

Quick Problem - Extracting numbers from a string

I need to extract a single variable number from a string. The string always looks like this:
javascript:change(5);
with the variable being 5.
How can I isolate it? Many thanks in advance.
Here is one way, assuming the number is always surrounded by parentheses:
var str = 'javascript:change(5);';
var lastBit = str.split('(')[1];
var num = lastBit.split(')')[0];
Use regular expressions:-
var test = "javascript:change(5);"
var number = new RegExp("\\d+", "g")
var match = test.match(number);
alert(match);
A simple RegExp can solve this one:
var inputString = 'javascript:change(5);';
var results = /javascript:change\((\d+)\)/.exec(inputString);
if (results)
{
alert(results[1]); // 5
}
Using the javascript:change part in the match as well ensures that if the string isn't in the proper format, you wont get a value from the matches.
var str = 'javascript:change(5);', result = str.match(/\((\d+)\)/);
if ( result ) {
alert( result[1] )
}

Categories

Resources