Retrieve substring between two characters - javascript

I have string like this
var str = "#it
itA
itB
_
#et
etA
etB
_
etC
etD"
How can I retrieve elements between # and _. As of now I am splitting the text with new line but unable to workout this. Please help me on this. Please use this fiddle http://jsfiddle.net/h728C/2/

IF you simply want the FIRST string BETWEEN you can use:
var mys= str.substring(str.indexOf('#')+1,str.indexOf("_"));
this returns: "it itA itB"

I've posted some solution in fidde. It uses the Regex
var str = $('#a').text();
var pattern = /#([\s\S]*?)(?=_)/g;
var result = str.match(pattern);
for (var i = 0; i < result.length; i++) {
if (result[i].length > 1) {
result[i] = result[i].substring(1, result[i].length);
}
alert(result[i]);
}
Strip the end and beginning.
Edit
I've updated the fiddle and the code. Now it strips the beginning # and ending _.
You can use either. Whichever is convenient.
​
​

I don't really get why but this works:
var str = $('#a').text();
var results = [];
$.each(str.split("_"), function(){
var a = this.toString().split("#");
if(a.length===2) results.push(a[1]);
});
console.log(results);​

You can use this kind of regex:
str.replace(/\s/g, "").match(/#(.*?)_/g, "$1");
See this fiddle.

one line solution to get the array
var arrStr = str.split(/[#_]/);

I would not recommend using regex here as it can be done more efficiently through other methods.
function extractString(template, initChar, finalChar) {
let i = 0;
let data = [];
do {
if (template[i] == initChar) {
for (let j = i + 1; j < template.length; j++) {
if (template[j] == finalChar) {
data[data.length] = template.slice(i + 1, j);
i = j + 1;
break;
}
}
}
}
while (++i < template.length);
console.log(data)
return data;
}
extractString("#adj#, #brown# fox jumps over the lazy #dog#.","#","#");

Related

Get all text from a Div after a '-' up until the first character

I'm trying to write a function that will find an instance of text within a div and console.log all text that is after the '-' character. After the '-' character there are sometimes spaces and tabs, so I want to remove these up until the first text character. Here's what I have so far (that is not working at all):
var countryData = $(".countries-title").next().text();
//var regex = /(?<= - ).*/g;
let stringArray = countryData.replace(/\t/g, '').split('\r\n');
console.log(stringArray);
Any help is appreciated. Thanks
console.log('here is a - whole bunch of text'.match(/-\s*(.*)$/)[1]) will log out "whole bunch of text". Is that along the lines of what you are looking for? Let me know if you want me to elaborate.
Assuming you want to maintain all hyphens and formatting after the first hyphen and subsequent spaces you could use:
let textAfterHyphen = countryData.replace(/\s*-\s*/, '');
I am not sure if I understood all but here you have my solution:
$(document).ready(function returnString() {
$("#click-target").on("click",function(){
var newString = [];
var resultString = [];
var onlyChar =$(".target").text();
newString = onlyChar.split("");
for(var i = 0; i < newString.length; i++){
if(newString[i] == "-"){
resultString = newString.slice(i+1,newString.length).join("");
}
}
var k = 0;
for(var j = 0; j < resultString.length; j++){
if(resultString.charCodeAt(j) > 64 && resultString.charCodeAt(j) < 91){
k += j;
}
}
console.log(resultString.slice(k,resultString.length));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="target">Text- *^^^***Text to display</div>
<button id ="click-target">Click</button>

Regex: ccTLD wildcard detection/removal in Javascript?

I have an url like this one:
http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html
But the ".com" over there can change depending on the country, so that url also works with:
http://xenodesystems.blogspot.mx/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html
http://xenodesystems.blogspot.it/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html
http://xenodesystems.blogspot.fr/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html
etc.
What I need to do is replacing "xenodesystems.blogspot.*" with "blog.xenodesystems.com" and leave the rest of the URL intact, like this:
http://blog.xenodesystems.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html
Is this possible to do with javascript? I know blogger can redirect a domain, but I need to do it in pure Javascript explicitly. I know it's possible, it's just matter of finding the right regex, right?
Try this (JSFIDDLE). No regular expressions so it's much more efficient:
var str="http://xenodesystems.blogspot.mx/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html";
function xIndexOf(Val, Str, x)
{
if (x <= (Str.split(Val).length - 1)) {
Ot = Str.indexOf(Val);
if (x > 1) { for (var i = 1; i < x; i++) { var Ot = Str.indexOf(Val, Ot + 1) } }
return Ot;
}
}
var slash = (xIndexOf('/',str,3));
var dot = (xIndexOf('.',str,2));
str = str.substring(0,dot)+".com"+str.substring(slash)
alert(str)
xIndexOf function taken from here.
I think this is what you mean:
var urls = [
'http://xenodesystems.blogspot.mx/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html',
'http://xenodesystems.blogspot.it/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html',
'http://xenodesystems.blogspot.fr/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html',
'http://xenodesystems.blogspot.com.au/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html',
];
var ret = new Array;
var len = urls.length;
for (var i = 0; i < len; ++i) {
ret.push(urls[i].replace(/xenodesystems.blogspot(?:\.[a-zA-Z]+)+/,'xenodesystems.blogspot.com'));
}
console.log(ret);
OUTPUT
["http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html",
"http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html",
"http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html",
"http://xenodesystems.blogspot.com/2013/07/actualizarmigrar-ruby-20-y-rails-4-sin.html"]
Here's a fiddle

how to extract numbers from string using Javascript?

how to extract numbers from string using Javascript?
Test cases below:
string s = 1AA11111
string s1= 2111CA2
string s result = 111111
string s1 result = 211112
My code below is not working:
var j = 0;
var startPlateNums = "";
while (j <= iStartLength && !isNaN(iStartNumber.substring(j, j + 1))){
startPlateNums = startPlateNums + iStartNumber.substring(j, j + 1);
j++;
}
How about a simple regexp
s.replace(/[^\d]/g, '')
or as stated in the comments
s.replace(/\D/g, '')
http://jsfiddle.net/2mguE/
You could do:
EDITED:
var num = "123asas2342a".match(/[\d]+/g)
console.log(num);
// THIS SHOULD PRINT ["123","2342"]
A regex replace would probably the easiest and best way to do it:
'2111CA2'.replace(/\D/g, '');
However here's another alternative without using regular expressions:
var s = [].filter.call('2111CA2', function (char) {
return !isNaN(+char);
}).join('');
Or with a simple for loop:
var input = '2111CA2',
i = 0,
len = input.length,
nums = [],
num;
for (; i < len; i++) {
num = +input[i];
!isNaN(num) && nums.push(num);
}
console.log(nums.join(''));

Generate Array Javascript

I want to generate an array in jQuery/JS, which contains "code"+[0-9] or [a-z].
So it will look like that.
code0, code1 ..., codeA, codeB
The only working way now is to write them manually and I am sure this is a dumb way and there is a way to generate this automatically.
If you give an answer with a reference to some article where I can learn how to do similar stuff, I would be grateful.
Thank you.
For a-z using the ASCII table and the JavaScript fromCharCode() function:
var a = [];
for(var i=97; i<=122; i++)
{
a.push("code" + String.fromCharCode(i));
}
For 0-9:
var a = [];
for(var i=0; i<=9; i++)
{
a.push("code" + i);
}
I'm using the unicode hexcode to loop through the whole symbols from 0-z:
var arr = [];
for (var i = 0x30; i < 0x7b;i++){
// skip non word characters
// without regex, faster, but not as elegant:
// if(i==0x3a){i=0x41}
// if(i==0x5b){i=0x61}
char = String.fromCharCode(i);
while(!/\w/.test(char)){char = String.fromCharCode(i++)};
// generate your code
var res = "code"+char;
// use your result
arr.push(res);
}
console.log(arr);
Here goes your example.
Docs:
Unicode Table
for loop
fromCharCode
JS Array and it's methods
you can generate array in javascript by using following code.
var arr = [];
for (var i = 0; i < 5; i++) {
arr.push("code"+ i);
}
please refer following links.
https://developer.mozilla.org/en/docs/JavaScript/Reference/Global_Objects/Array
http://www.scriptingmaster.com/javascript/JavaScript-arrays.asp
a = [];
for(i = 48; i < 91; i++) {
if (i==58) i = 65
a.push("code" + String.fromCharCode(i));
}
alert(a.join(',')) // or cou can print to console of browser: console.log(a);

JS/jQuery: how many character occurance in textarea

Assuming:
str value = 'This is some text';
I want to count how many 't' occurrences, how to do that?
It is much easier with regex
var regex = new RegExp("t", "gi")
var count = "This is some text".match(regex).length;
Will give you counts of t in the given string(ignore case).
You can test it here.
Further reference
RegExp 1
RegExp 2
String
String.match()
var sValue = 'This is some text';
var tCount = sValue.split("t").length - 1;
alert("t appears " + tCount + " times");
If you want to count occurrences of all letters, you better use one loop as shown in the other answers.
An easy solution is to loop
var count = 0;
for(var i = 0; i < str.length; i ++) {
if(str.charAt(i) === 't')
++count;
}
You might also want to use str.toLowerCase(); if you don't want to be case sensitive.
I think you all make it more complicated than it needs to be. Use regex. This is also case insensitive. If you want case sensitive, remove the i after g.
var str = "This is some text";
var pattern = /t/gi;
alert(str.match(pattern).length);
Make it shorter.
var str = "This is some text";
alert(str.match(/t/gi).length);
Several ways to do this...
function countChar(str, searchChar) {
var num=0;
for (var i=0; i<str.length; ++i) {
if (str[i] == searchChar)
++num;
}
return num;
}
use like:
numt = countChar('This is some text', 't');
May be can help you here
.replace().length
with regards
Wazzy
<button onclick="alert(countCharacter('abcdea', 'a'));"> Test! </button>
<script type="text/javascript">
function countCharacter(sample, characterToFind) {
var result = 0;
for(i = 0;i<sample.length;i++) {
if(sample[i] === characterToFind) {
result++;
}
}
return result;
}
</script>

Categories

Resources