简体   繁体   English

Javascript:如何剪切字符串的特定部分?

[英]Javascript: How to cut a specific part of a string?

THE SITUATION: 情况:

I need to cut a specific part of a string. 我需要剪切字符串的特定部分。 That part will not always be the same in length and content. 该部分的长度和内容并不总是相同的。

The only thing i know is that it will always start with: <style> and finish with: </style> 我唯一知道的是它将始终以: <style>开头并以: </style>

All the content in the middle must cut out (style tag included). 中间的所有内容都必须删除(包括样式标签)。


THE QUESTION: 问题:

How can i cut a specific part of a string knowing only the begin and the end of that part? 如何仅知道字符串的开始和结尾来剪切字符串的特定部分?

try something like this: 尝试这样的事情:

var str = '<style> p {margin: 0; } </style> other text';
var result = str.replace(/\<style\>.*\<\/style\>/, '');

DEMO DEMO

UPD: For getting content in tag style (style tag included) try this: UPD:要获取标签style (包括样式标签)的内容,请尝试以下操作:

var result = str.match(/\<style\>.*\<\/style\>/)[0]

DEMO DEMO

You can manipulate DOM directly with javascript without regex or jquery. 您可以使用javascript直接操作DOM,而无需使用正则表达式或jquery。 You need to select the parent element of the target element/class/id and then remove the child. 您需要选择目标元素/类/ id的父元素,然后删除子元素。

HTML: HTML:

<html>
  <head>
    <style>
      body {color:blue;}
    </style>
  </head>
  <body>

JavaScript: JavaScript的:

var text = document.querySelectorAll("style")[0];
text.parentNode.removeChild(text);

Demo in https://jsfiddle.net/kt6feq92/ https://jsfiddle.net/kt6feq92/中进行演示

Suppose you have following string 假设您有以下string

var str = '<style>I am a style</style>';
var res = str.replace("<style>", "").replace("</style>", "");
alert(res);

Demo 演示

Get the part string: 获取零件字符串:

theString = 'asdfasdf<style>aaaaaaaaaaaaaa</style>bbbbbbbb'
targetString= theString.replace(/<\/style>/ig,'<style>').split('<style>')[1];

Delete the whole string: 删除整个字符串:

theString = 'asdfasdf<style>aaaaaaaaaaaaaa</style>bbbbbbbb'
targetString= theString.replace(/<style>.*<\/style>/ig,'');

You may be looking for a regex . 您可能正在寻找正则表达式

The following regex will select the string that is between <style></style> tags: 以下正则表达式将选择<style></style>标记之间的字符串:

\<style\>(.*)\<\/style\>/s

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM