Menú Cerrar
métodos de javascript

En entradas anteriores hicimos una introducción a la programación donde vimos temas relacionados con la programación en general. Hablamos de estructura de datos, funciones, etcétera. Ahora, nos vamos a enfocar en algo muy importante. Para un programador de JavaScript lidiar con el manejo de string es un pan de cada día. ¿Qué mejor manera de hacerlo que tener a tu alcance una lista de los métodos más comunes para el manejo de string en javascript? Es por eso que en esta entrada te presento una lista de los métodos más comunes para el manejo de string en JavaScript. ¿Eres un programador de Python? Consulta esta lista de métodos para el manejo de string en Python.

string en javascript

Lista de los métodos para el manejo de string en JavaScript

chartAt()

Dada una cadena de texto, este método devuelve la letra que está en la posición mencionada. En el código a continuación, la salida es “H”.

var texto="Hola mundo";
console.log(texto.charAt(0));

concat()

Dadas dos cadenas de textos, este método concatena las cadenas en el orden especificado por el programador. A continuación, te presento un ejemplo.

var texto="Hola mundo ";
var texto1="Soy un desarrollador JavaScript"
console.log(texto.concat(texto1));

indexOf()

Dada una cadena de texto y una palabra a buscar en el texto, este método devuelve el primer índice donde se encuentra la primera letra de la palabra en la cadena. A continuación, te presento un ejemplo.

var texto="Hola mundo, Soy un desarrollador JavaScript.";
console.log(texto.indexOf("un"));

lastindexOf()

Dada una cadena de texto y una palabra a buscar en el texto, este método devuelve la posición donde se encuentra la primera letra de la palabra en la cadena. No lo confundas con el método anterior. A continuación, te presento un ejemplo.

var texto="Hola mundo, Soy un desarrollador JavaScript.";
console.log(texto.lastIndexOf("un"));

replace()

Dada una cadena de texto, este método permite buscar una palabra en la cadena y sustituirla por otra. Recibe dos argumentos: el primero, la palabra a se sustituida y el segunda la palabra que sustituirá a la otra. A continuación, te presento un ejemplo.

var texto="Hola mundo, Soy un desarrollador JavaScript.";
console.log(texto.replace("Soy un", "soy el"));

Recuerda que el método sustituye la primera coincidencia, así que tienes que tener cuidado con eso.

search()

Este método es similar al indexOf.

slice()

Dada una cadena de texto, este método permite recortar la cadena en una longitud especificada por el usuario. Recibe dos métodos: el inicio y el final del recorte. A continuación, te presento un ejemplo.

var texto="Hola mundo, Soy un desarrollador JavaScript.";
console.log(texto.slice(0,5));

substr()

Dada una cadena de texto, este método permite recortar la cadena en una longitud especificada por el usuario. Recibe dos métodos: el inicio y la cantidad de palabras a recortar. No lo confundas con el slice. A continuación, te presento un ejemplo.

var texto="Hola mundo, Soy un desarrollador JavaScript.";
console.log(texto.substr(0,7));

substring()

Este método es similar al slice.

toUpperCase()

Dada una cadena de texto, este método permito convertirlo a mayúscula. A continuación, te presento un ejemplo.

var texto="Hola mundo, Soy un desarrollador JavaScript.";
console.log(texto.toUpperCase());

 valueOf()

El método valueOf de String devuelve el valor primitivo de un objeto String como un tipo de dato cadena. A continuación, te presento un ejemplo.

const texto = String('Hola mundo');
console.log(texto.valueOf());

typeOf()

Dada una variable, este método permite saber el tipo de dato de dicha variable. A continuación, te presento un ejemplo.

var texto1 = 'Hola mundo';
var texto2 = 5;
var texto3 = true;
console.log(typeof texto1);
console.log(typeof texto2);
console.log(typeof texto3);

trim()

Este método te permite quitar espacios en blanco al inicio y al final de una cadena. A continuación, te presento un ejemplo.

var texto1 = '    Hola mundo     ';
console.log(texto1.trim());

toString()

Este método te permite convertir un valor a string. A continuación, te presento un ejemplo.

var texto1 = 5;
console.log(typeof texto1);
console.log(typeof texto1.toString());

includes()

Dada una cadena de texto y una cadena a buscar en este texto, este método devuelve true si la cadena a buscar está en la cadena, en caso contrario devuelve false. A continuación, te presento un ejemplo.

var texto1 = "Hola, soy un pro en JavaScript";
console.log(texto1.includes("soy"));
console.log(texto1.includes("java"));

charCodeAt()

Devuelve el Unicode del carácter que está en el índice mencionado. A continuación, te presento un ejemplo.

var texto1 = "Hola, soy un pro en JavaScript";
console.log(texto1.charCodeAt(7));

match()

Este método permite buscar un valor en una cadena e imprime este valor si existe y la cantidad de veces que se encuentra. En caso contrario imprime null. A continuación, te presento un ejemplo.

var texto1 = "Hola, soy un pro en JavaScript";
console.log(texto1.match(/soy/));

split()

Permite dividir una cadena por el carácter especificado. A continuación, te presento un ejemplo.

var texto1 = "1,2,3,4,5,6,7";
console.log(texto1.split(","));

toLowerCase()

Permite convertir una cadena a minúscula. A continuación, te presento un ejemplo.

var texto1 = "HOLA";
console.log(texto1.toLowerCase());

Resumen

En esta entrada vimos los métodos más comunes para manejar string en JavaScript. Si me faltan algunos, colabora dejando su nombre y lo agregaré.

Acerca del autor

Saintus Zephir

Ingeniero en Sistemas Computacionales y estudiante de Maestría en Ciencias en Ingeniería y Tecnologías Computacionales en el Centro de Investigación y de Estudios Avanzados del IPN (CINVESTAV-IPN).

Comparte el artículo en tus redes sociales

Artículos relacionados

73 comentarios

  1. Fix

    Muy completo la verdad, lo recomiendo 😁. Pero tienes una falta de ortografía en la versión en inglés en la sección charCodeAt (). 😉

  2. Anónimo

    That’s a very good article about JavaScript. Is it possible to translate it to English?

  3. Johnnie

    Hey! Quick question that’s completely off topic.

    Do you know how to make your site mobile friendly?
    My blog looks weird when viewing from my iphone4. I’m trying to find a
    theme or plugin that might be able to resolve this problem.
    If you have any suggestions, please share. Many thanks!

  4. Modesta

    I was suggested this blog by my cousin. I am not sure whether this post is written by him
    as no one else know such detailed about my problem.

    You’re wonderful! Thanks!

  5. http://tinyurl.com/ybp6oq5d

    Does your site have a contact page? I’m having problems locating it but, I’d
    like to send you an email. I’ve got some creative ideas for your blog you might be
    interested in hearing. Either way, great site and I look forward to seeing it expand over time.

  6. http://tinyurl.com/

    Thank you for the auspicious writeup. It in fact was a amusement account it.
    Look advanced to more added agreeable from you! However, how can we communicate?

  7. cheapest flight tickets

    I know this site presents quality based articles and other material, is there any other web page which provides these kinds of data in quality?

  8. affordable airfare

    I was pretty pleased to discover this web site.
    I want to to thank you for ones time for this particularly wonderful read!!
    I definitely loved every bit of it and I have you book marked to check out new things in your web site.

  9. cheapest airline tickets possible

    Hello there! This blog post couldn’t be written any
    better! Looking at this post reminds me of my previous roommate!
    He constantly kept talking about this. I am going
    to forward this article to him. Fairly certain he’ll have a
    great read. Thanks for sharing!

  10. gamefly

    Having read this I believed it was rather informative. I appreciate you taking the time and effort to put this article together.
    I once again find myself spending a lot of time both reading and leaving comments.

    But so what, it was still worthwhile!

  11. gamefly

    Hey there exceptional blog! Does running a blog similar to this require a lot of work?
    I have virtually no expertise in programming however I had been hoping to start my own blog in the near future.
    Anyhow, if you have any ideas or techniques for new blog owners please
    share. I understand this is off subject however I simply had to ask.
    Thanks!

  12. http://tinyurl.com/yxwoztup

    What’s Happening i am new to this, I stumbled upon this I’ve
    discovered It absolutely useful and it has aided me out loads.
    I hope to contribute & aid other users like its helped me.

    Great job.

  13. http://tinyurl.com

    Wonderful site. Lots of helpful information here. I am sending it
    to a few pals ans also sharing in delicious. And naturally, thanks in your sweat!

  14. tinyurl.com

    I pay a visit day-to-day some web sites and information sites to read posts, however this web site presents feature based articles.

  15. http://bit.ly/3x6IO2H

    Superb blog! Do you have any suggestions for aspiring writers?
    I’m planning to start my own blog soon but I’m a little lost on everything.

    Would you propose starting with a free platform like WordPress or go for a paid option? There are so many choices out
    there that I’m completely overwhelmed .. Any ideas? Appreciate it!

  16. tinyurl.com

    Wow, marvelous blog layout! How long have you been blogging for?

    you made blogging look easy. The overall look of your web site is great, as well as the content!

  17. bit.ly

    Nice post. I used to be checking continuously this blog and I am impressed!

    Extremely useful info specially the closing phase 🙂 I take care of such information much.

    I was looking for this certain info for a very long time. Thanks
    and best of luck.

  18. TrudeysaPi

    characteristics of critical thinking
    [url=”https://criticalthinking2020.net”]how to develop critical thinking skills[/url]
    synonym for critical thinking

  19. http://tinyurl.com/2cznv4u8

    Hello! I’ve been reading your site for a while now and finally got the bravery to go ahead and give you a
    shout out from Atascocita Texas! Just wanted
    to tell you keep up the great job!

  20. http://bit.ly

    I am sure this piece of writing has touched all the internet
    visitors, its really really nice paragraph on building up new webpage.

  21. GlynnissaPi

    masters dissertation help
    [url=”https://dissertationhelpexpert.com”]need help[/url]
    dissertation help methodology

  22. SuzannsaPi

    dissertation writing services
    [url=”https://dissertationhelpspecialist.com”]dissertation help for phd candidates[/url]
    dissertation help

  23. SallisaPi

    dissertation writing skills
    [url=”https://dissertationwritingcenter.com”]writing dissertation[/url]
    writing a proposal for your dissertation

  24. DarsiesaPi

    buy dissertations online
    [url=”https://examplesofdissertation.com”]dissertation research[/url]
    proposal and dissertation help 2000 words

  25. TandisaPi

    online casinos no deposit bonus
    [url=”https://1freeslotscasino.com”]no deposit casino games[/url]
    online casinos for real money

  26. tinyurl.com

    Hi there, I discovered your web site by the use of
    Google even as looking for a similar matter, your web site got
    here up, it seems to be good. I’ve bookmarked it in my google bookmarks.

    Hello there, simply became alert to your blog thru
    Google, and located that it is really informative.
    I am going to be careful for brussels. I will
    be grateful in the event you proceed this in future.
    A lot of other folks will be benefited from your writing.
    Cheers!

  27. MabellesaPi

    dissertation writing services reviews
    [url=”https://helpwithdissertationwritinglondon.com”]dissertation proposal writing[/url]
    mathematics dissertation help

  28. TandisaPi

    online casino best welcome bonus
    [url=”https://1freeslotscasino.com”]free casino bonus[/url]
    real money casino online

  29. JenneesaPi

    dissertation completion pathway
    [url=”https://professionaldissertationwriting.com”]writing editing services[/url]
    dissertation writing advice

  30. AbagaelsaPi

    casino welcome bonuses
    [url=”https://9lineslotscasino.com”]biggest online casino bonuses[/url]
    free spins casino

  31. HerminasaPi

    dissertation defense
    [url=”https://professionaldissertationwriting.org”]dissertation help service[/url]
    best dissertation writing service

  32. tinyurl.com

    Hey just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading properly.

    I’m not sure why but I think its a linking issue.
    I’ve tried it in two different browsers and both show
    the same results.

  33. ShaylasaPi

    best online casino to win money
    [url=”https://all-online-casino-games.com”]online casino free money[/url]
    online casinos for us players

  34. AudresaPi

    dissertation thesis writing
    [url=”https://writing-a-dissertation.net”]medical dissertation writing services[/url]
    dissertation help for phd candidates

  35. VerenasaPi

    online mobile casinos
    [url=”https://casino8online.com”]online usa casino[/url]
    deposit bonus casino

  36. HestiasaPi

    uk dissertation help
    [url=”https://writingadissertationproposal.com”]doctoral dissertation help[/url]
    custom dissertation writing

  37. DixiesaPi

    online casino play for real money
    [url=”https://casino-online-jackpot.com”]online real casino[/url]
    online casino win real money

  38. LaureensaPi

    online casino bonus
    [url=”https://casino-online-roulette.com”]casino free bonus[/url]
    casino usa online

  39. tinyurl.com

    I’m very pleased to find this web site. I wanted to thank you for ones time just for
    this wonderful read!! I definitely appreciated every bit of it and
    I have you book-marked to look at new information in your blog.

  40. FrannisaPi

    best online casino
    [url=”https://cybertimeonlinecasino.com”]real casino games online[/url]
    casino games that pay real money

  41. PearlsaPi

    free casinos bonus
    [url=”https://download-casino-slots.com”]online casinos[/url]
    best online bingo

  42. BobbiesaPi

    best casino bonus
    [url=”https://firstonlinecasino.org”]casino free bonus[/url]
    mobile casino games for real money

  43. LesliesaPi

    biggest online casino bonuses
    [url=”https://free-online-casinos.net”]best casino bonuses[/url]
    bovada online casino

  44. TrudiesaPi

    best online casino welcome bonus
    [url=”https://internet-casinos-online.net”]no deposit casino online[/url]
    free sign up bonus

  45. HonorsaPi

    zenmate vpn
    [url=”https://freehostingvpn.com”]buy vpn for windows[/url]
    buy vpn software

  46. 78invest.fr

    You ought to be a part of a contest for one of the most useful sites on the internet.
    I’m going to recommend this website!

  47. JaynellsaPi

    live online casino usa
    [url=”https://newlasvegascasinos.com”]casino bonuses[/url]
    no deposit casino real money

  48. TeddiesaPi

    hotspot shield free vpn
    [url=”https://freevpnconnection.com”]is avast vpn any good[/url]
    whats a vpn

  49. sawomenfightback.com

    Howdy! I know this is kind of off topic but I was wondering if
    you knew where I could locate a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having difficulty finding one?
    Thanks a lot!

  50. DulceasaPi

    casino games for real money
    [url=”https://onlinecasinofortunes.com”]best online casino usa[/url]
    real money online casinos

  51. JenneesaPi

    vpn service free
    [url=”https://imfreevpn.net”]free vpn browser[/url]
    best vpn for tor

  52. CarolansaPi

    no deposit casino bonuses
    [url=”https://onlinecasinosdirectory.org”]usa casinos online[/url]
    best casino deposit bonus

  53. FanyasaPi

    no deposit casino bonuses
    [url=”https://onlineplayerscasino.com”]online casino no deposit bonus 2021[/url]
    play bingo for real money

  54. KelseysaPi

    buy secure vpn
    [url=”https://rsvpnorthvalley.com”]best vpn for linux[/url]
    best vpn for gaming reddit

  55. http://tinyurl.com/2h5jpdfg

    I do not know if it’s just me or if everyone else experiencing issues
    with your blog. It looks like some of the written text on your posts are running off the screen. Can someone else please comment and let me know
    if this is happening to them as well? This might be a issue with my browser because I’ve had this happen before.
    Thank you

  56. CarolinsaPi

    top usa online casinos
    [url=”https://ownonlinecasino.com”]online casinos real money no deposit[/url]
    online casinos no deposit

  57. http://tinyurl.com/

    Hi would you mind stating which blog platform you’re using?

    I’m looking to start my own blog in the near future but I’m having a hard time choosing between BlogEngine/Wordpress/B2evolution and Drupal.

    The reason I ask is because your layout seems different then most blogs and I’m looking for something completely unique.
    P.S Apologies for getting off-topic but I had to ask!

Deja una respuesta

Tu dirección de correo electrónico no será publicada.

× ¿Cómo puedo ayudarte?